There are following way to get the second character of a string in Java 8.
- First convert Arrays to list using Arrays.asList() method.
- Now get the Stream data from List using arrayList.stream() method.
Using map() method:-
- Through Stream.map() operation transforms the elements of a stream from one type to another.
- Inside there we are use the s.charAt(2) to returns the character at the specified index in a string.
Using flatMap() method:-
- flatMap() method first transforms each list of words into a stream of words.
- Stream.of method is used to create a stream from one or more elements.
- Inside there we are use the s.charAt(2) to returns the character at the specified index in a string.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SecondChar {
public static void main(String[] args) {
List<String> list = Arrays.asList("Apple", "mango", "orange", "watermelon");
List<Character> check = list.stream().map(s -> s.charAt(2)).collect(Collectors.toList());
System.out.println("second char using map:- " + check);
List<Character> ch = list.stream().flatMap(t -> Stream.of(t.charAt(2))).collect(Collectors.toList());
System.out.println("second char using flatMap:- " + ch);
}
}
Output :-
second char using map:- [p, n, a, t]
second char using flatMap:- [p, n, a, t]