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
@RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
Centralized error handling in Spring
exception-handling
problemdetail
rest-api
Intermediate
7 steps
java
@Component @Order(20) public class ProductSearchIndexRunner implements ApplicationRunner {
Rebuilding a search index at Spring startup
startup-hook
batching
streaming
Intermediate
8 steps
java
public final class FileChecksum { private static final char[] HEX = "0123456789abcdef".toCharArray();
Streaming a SHA-256 file checksum in Java
hashing
streams
resource-management
Intermediate
7 steps
java
@Service public class OrderCheckoutService { private final OrderRepository orderRepository;
How @Transactional guards a Spring checkout
dependency-injection
transactions
atomicity
Intermediate
6 steps
java
@Service public class OrderMetricsService { private final MeterRegistry registry;
Instrumenting orders with Micrometer in Spring
metrics
micrometer
observability
Intermediate
8 steps
java
@RestController @RequestMapping("/api/files") public class FileUploadController {
Handling secure file uploads in Spring
file-upload
input-validation
path-traversal
Intermediate
10 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.