Member-only story
Why Every Java Developer Should Know FlatMap
If you’re a Java developer, you’ve probably worked with collections and streams. But there’s one powerful operation that many developers either don’t know about or don’t fully understand: flatMap. In this article, we’ll explore what flatMap is, why it’s useful, and how it can make your code cleaner and more efficient.
What is flatMap?
At its core, flatMap is like a combination of two operations: mapping (transforming) elements and then flattening the results into a single stream. Think of it as opening a bunch of boxes that each contain smaller boxes, and then putting all the items from those smaller boxes into one big container.
Let’s break this down with a simple example:
List<List<Integer>> nestedNumbers = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
// Using flatMap to flatten the nested lists
List<Integer> flattenedNumbers = nestedNumbers.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]