java 32 lines · 7 steps

Flattening nested data with Java streams

Four stream pipelines show how flatMap collapses nested collections before transforming and aggregating them.

Explained by highlit
1public List<String> collectTagsFromArticles(List<Article> articles) {
2 return articles.stream()
3 .flatMap(article -> article.getTags().stream())
4 .map(String::trim)
5 .filter(tag -> !tag.isEmpty())
6 .map(String::toLowerCase)
7 .distinct()
8 .sorted()
9 .collect(Collectors.toList());
10}
11 
12public Map<String, Long> countLineItemsByCategory(List<Order> orders) {
13 return orders.stream()
14 .flatMap(order -> order.getLineItems().stream())
15 .collect(Collectors.groupingBy(
16 item -> item.getProduct().getCategory(),
17 Collectors.counting()
18 ));
19}
20 
21public List<Coordinate> flattenGrid(List<List<Coordinate>> rows) {
22 return rows.stream()
23 .flatMap(List::stream)
24 .collect(Collectors.toList());
25}
26 
27public OptionalDouble averageScoreAcrossExams(List<Student> students) {
28 return students.stream()
29 .flatMapToInt(student -> student.getExams().stream()
30 .mapToInt(Exam::getScore))
31 .average();
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1flatMap turns a stream of collections into one flat stream you can process uniformly.
  2. 2Collectors like groupingBy and counting fold a stream into a summarized data structure in one pass.
  3. 3Primitive stream variants such as flatMapToInt unlock numeric operations like average without boxing.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Flattening nested data with Java streams — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code