What is Collectors.flatMapping() in Java?

What is the Collectors class?

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() method

flatMapping() 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 flat mapping function converts an input element into a stream with zero or more output elements. These elements are then added downstream. After the contents of each mapped stream have been put downstream, the stream is closed.
  • This method is usually used when a method accepts one input and produces multiple outputs.
  • This method was introduced in Java’s version 9.

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;

Syntax


public static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream)

Parameters

  • 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.

Return value

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.

Code

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);
}
}

Explanation

  • Lines 1-3: We import the relevant packages.
  • Line 8: We create a list of integers called integerList.
  • Line 10: We print the integerList to the console.
  • Line 12: We create a stream from the integerList called integerStream.
  • Lines 14-15: We then apply the 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.
  • Line 17: We print flattenedList to the console.

Free Resources