Java flatMap Function Guide
In Java, flatMap is an intermediate operation that maps each element in a stream to another stream, and then combines all these streams into one.
Specifically, the input of the flatMap operation is a stream, and the output is a new stream. For each element in the input stream, flatMap maps it to another stream, and then merges these streams into one stream. This merged stream contains all the elements of the mapped streams.
Using the flatMap operation helps flatten the structure of a stream. For example, if each element in the original stream is a list, using flatMap will merge these lists into a single stream instead of nested streams. This simplifies stream operations, making the code clearer and more concise.
Here is an example demonstrating the usage of flatMap operation:
List<List<Integer>> numbers = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
List<Integer> flattenedNumbers = numbers.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedNumbers); // 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9]
In the example above, each element in the original stream numbers is a list. We use the flatMap operation to merge these lists into one stream, and then collect the merged stream into a new list. The final output of the flattenedNumbers list contains all elements without nesting.