Java Stream.flatMap Method
Java 8 Stream.flatMap() method is used to flatten stream of collections to a stream of objects. In short, we can say that it allows us to combine the objects from multiple collections into a single collection.
Flattening Example
Before flattening: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After flattening: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Stream flatMap Examples
Codes for flattening nested lists
private static void flatteningNestedLists() {
List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(1,2,3),
Arrays.asList(4,5,6),
Arrays.asList(7,8,9)
);
List<Integer> results = listOfLists.stream()
.flatMap(Collection::stream)
.toList();
log.info("results: {}", results);
}
Codes for flattening nested arrays
private static void flatteningNestedArrays() {
Integer[][] nestedArrays = new Integer[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
List<Integer> results = Arrays.stream(nestedArrays)
.flatMap(Arrays::stream)
.toList();
log.info("results: {}", results);
}