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
public final class CircuitBreaker { private enum State { CLOSED, OPEN, HALF_OPEN }
How a circuit breaker guards failing calls
state-machine
resilience
concurrency
Advanced
7 steps
java
public Map<Long, CustomerDto> indexByCustomerId(List<CustomerDto> customers) { return customers.stream() .collect(Collectors.toMap( CustomerDto::getId,
Building maps from lists with Collectors.toMap
streams
collectors
maps
Intermediate
5 steps
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") @Validated public class ProductSearchController {
Validating query params in a Spring controller
validation
pagination
rest-api
Intermediate
8 steps
java
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = PasswordsMatchValidator.class) public @interface PasswordsMatch {
Custom cross-field validation in Spring
bean-validation
custom-constraints
cross-field-validation
Intermediate
8 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.