Sitemap
Javarevisited

A humble place to learn Java and Programming better.

Member-only story

Everything You Must Know About FlatMap in Java

--

Java Streams operations are widely used in modern Java Programming. Map () and flatMap() are the important ones that we should understand to transform streams efficiently.

My articles are free for everyone. Non-members can read this full article for free HERE.

What is flatMap()?

The flatMap() operation transforms each element of a stream to zero, one, or multiple elements.

It uses a function that returns a stream for each input stream element. flatMap() then flattens these multiple output streams into a single one.

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

List<Integer> flattenedList = listOfLists.stream()
.flatMap(List::stream) // Flatten the Stream<List<Integer>> into Stream<Integer>
.collect(Collectors.toList());

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

In the above example, we can see that we have transformed multiple lists into a single list by flattening all those previous streams.

map() vs flatMap in Java

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Saquib Aftab
Saquib Aftab

Written by Saquib Aftab

Lead Software Engineer | Java | Technology | Productivity | Learning and Improving to become a better developer

No responses yet