ProLesson 8.6Intermediate2 min readUpdated 30 October 2026
flatMap, reduce and sorting
Flatten nested data with flatMap, combine values with reduce, sort and limit results, and solve classic stream interview problems.
Three more stream tools complete your kit: flatMap for nested data, reduce for combining values into one, and sorting with limits for "top N" questions.
01map vs flatMap
map turns each element into one new element. flatMap turns each element into a stream of elements, then joins all of those streams into one flat stream:
FlatMap.java
import java.util.Arrays;
import java.util.List;
record Order(String id, List<String> items) { }
public class FlatMap {
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("A", List.of("pen", "book")),
new Order("B", List.of("bag")),
new Order("C", List.of("pen", "ink")));
List<List<String>> nested = orders.stream().map(Order::items).toList();
List<String> flat = orders.stream().flatMap(o -> o.items().stream()).distinct().toList();
System.out.println(nested);
System.out.println(flat);
List<String> lines = List.of("learn java", "learn kafka daily");
long words = lines.stream().flatMap(l -> Arrays.stream(l.split(" "))).count();
System.out.println(words);
}
}[[pen, book], [bag], [pen, ink]] [pen, book, bag, ink] 5
Loading the rest of the lesson…