We will compare the list conversion when using the for statement and when using the Stream map. Use the list below.
stream-map.java
final List<String> months =
Arrays.asList("January", "February", "March", "April", "May", "June", "July", "Augast", "September", "October", "November", "December");
Make a list consisting of only the first letter of each element.
We declare an empty list to store the first character and store it character by character in the for loop.
for.java
final List<String> firstChars = new ArrayList<>();
for (String c : months) {
firstChars.add(c.substring(0,1));
}
for (String fc : firstChars) {
System.out.print(fc);
}
The output is as follows. JFMAMJJASOND
Although it has been rewritten to a functional type, an empty list must be prepared by the programmer.
forEach.java
final List<String> firstChars = new ArrayList<>();
months.forEach(c -> firstChars.add(c.substring(0,1)));
firstChars.forEach(System.out::print);
There is no step to prepare an empty list, and the result of extracting the first character from the list appears to be stored in the new list as is. Stream's map () method converts contiguous inputs into contiguous outputs.
stream-map.java
final List<String> firstChars = months.stream().map(c -> c.substring(0,1)).collect(Collectors.toList());
firstChars3.forEach(System.out::print);
The map () method guarantees that the list of inputs and the list of outputs have the same number of elements, but not necessarily for the data types. If you want to get the number of characters of each element, it is converted from the character string type to the numeric type and output.
The following does not prepare the converted list, but directly outputs the contents of the element with forEach. If that is the case, it can be described in one line.
stream-map2.java
months.stream().map(c -> c.length()).forEach(cnt -> System.out.print(cnt + " "));
//Output as 7 8 5 5 3 4 4 6 9 7 8 8
Recommended Posts