Collectors is a utility class that provides various implementations of reduction operations. This includes grouping elements, collecting them into different collections, summarizing them according to various criteria, etc. The different functionalities in the Collectors class are usually used as the final operation on streams.
flatMapping()
methodflatMapping()
is a static method of the Collectors
class that returns a Collector
. This method converts a Collector
accepting elements of one type to a Collector
that accepts elements of another type. It does so by applying a mapping function to every input element.
The flatMapping
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package. To import the class check the following import statement:
import java.util.stream.Collectors;
public static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream)
Function<? super T, ? extends Stream<? extends U>> mapper
: The mapping function applied to every input element.Collector<? super U, A, R> downstream
: The downstream collector to accumulate the results.This method returns a collector that performs the mapping function on the input elements. It then passes the flat mapped results to the downstream collector.
import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {public static void main(String[] args) {List<Integer> integerList = List.of(4, 3, 1, 5);System.out.println("Integer List - " + integerList);Stream<Integer> integerStream = integerList.stream();List<Integer> flattenedList = integerStream.collect(Collectors.flatMapping(e -> Stream.of(e + 1, e - 1),Collectors.toList()));System.out.println("Result of applying flatMapping method on the list - " + flattenedList);}}
integerList
.integerList
to the console.integerList
called integerStream
.flatMapping
collector. This collector applies the mapping function that emits a stream of two integer values for every input integer. Finally, the streams of two integer values are flattened and collected to a list called flattenedList
.flattenedList
to the console.