Java 8 Stream has map () and flatMap (). Let's examine the difference.
First of all, from the conclusion
-Map (T-> R) is a 1: 1 conversion of the T data type to the R data type.
-FlatMap (T-> Stream <R>) is a 1: N conversion from the data type of T toStream <R>.
Stream#map()
List<String> nameList = Arrays.asList("Tanaka", "Suzuki", "Takahashi");
Stream<Integer> stream = nameList.stream().map(x -> x.length());
System.out.println(stream.collect(Collectors.toList()));
The above execution result:
[6, 6, 9]
| Tanaka | Suzuki | Takahashi |
|---|---|---|
| ↓ | ↓ | ↓ |
| 6 | 6 | 9 |
It is a 1: 1 conversion from a character string (String) to a character string length (Integer) as described above.
Stream#flatMap()
List<String> nameList = Arrays.asList("Tanaka", "Suzuki", "Takahashi");
Stream<Object> stream = nameList.stream().flatMap(x -> Stream.of(x, x.length()));
System.out.println((stream.collect(Collectors.toList())));
The above execution result:
[Tanaka, 6, Suzuki, 6, Takahashi, 9]
| Tanaka | Suzuki | Takahashi |
|---|---|---|
| ↓ | ↓ | ↓ |
| Tanaka, 6 | Suzuki, 6 | Takahashi, 9 |
1: N conversion from character string (String) to [character string (String), character string length (Integer)]. However, in that case, a two-dimensional array is not generated and a flat Stream is returned.
Recommended Posts