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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1flatMap turns a stream of collections into one flat stream you can process uniformly.
- 2Collectors like groupingBy and counting fold a stream into a summarized data structure in one pass.
- 3Primitive stream variants such as flatMapToInt unlock numeric operations like average without boxing.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/flattening-nested-data-with-java-streams-explained-java-4f8f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.