Java flatMap Usage Guide

In Java, flatMap is a method of the Stream interface used to map each element of a stream to another stream, and then merge all the resulting streams into one. The usage is as follows:

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

The mapper parameter is a function that maps elements of the input stream to another stream. The flatMap method iterates through each element of the input stream, passes each element to the mapper function, and then merges the generated streams into one stream to return.

Below is a simple example illustrating the usage of flatMap.

List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(4, 5, 6);
List<Integer> numbers3 = Arrays.asList(7, 8, 9);

List<List<Integer>> listOfLists = Arrays.asList(numbers1, numbers2, numbers3);

List<Integer> flattenedList = listOfLists.stream()
                                        .flatMap(List::stream)
                                        .collect(Collectors.toList());

System.out.println(flattenedList); // 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]

In the example above, we first created a list containing three lists. Then we used the flatMap method to convert each sublist into a stream, and then merged all the generated streams into one stream. Finally, we used the collect method to convert the merged stream into a list.

By using the flatMap method, we can easily merge multiple lists into one list, or merge multiple streams into one stream for further operations.

bannerAds