Java Streams II: Collectors, groupingBy and flatMap
Six sales feed every example. toList and joining give [Emma, Jake, Sofia] and "North / South / West", groupingBy with counting and summingInt gives a count and a total per region, flatMap pours three orders' items into one list, and mapToInt sums 5400.
What you will learn
- Collect a stream into a List or one joined String
- Group items into a Map with groupingBy, then count or sum each group
- Flatten a list of lists with flatMap
- Add up a field with mapToInt and sum, and know when a plain loop is clearer
Before you start
- Java streams I: filter, map and reduce
- Java records
This time we collect stream results into a List, a String or a Map. Every example starts from the same six sales.
Meet the data: six sales
package org.studyeasy.s05l10;
import java.util.List;
// One sale: who sold it, in which region, and for how much
public record Sale(String rep, String region, int amount) {
// Our data set: these six sales feed every example
public static List<Sale> ledger() {
return List.of(
// rep region amount
new Sale("Emma", "North", 1200),
new Sale("Liam", "South", 800),
new Sale("Anna", "North", 450),
new Sale("Jake", "West", 1500),
new Sale("Sofia", "South", 950),
new Sale("Mark", "North", 500));
}
// Short toString, so a printed List or Map of sales stays readable
@Override
public String toString() {
return rep + " " + amount;
}
}
A record with a rep, a region and an amount, plus a static ledger() that hands back the six sales across North, South and West.
Collect into a List or a String
List<String> bigSellers = Sale.ledger().stream()
.filter(s -> s.amount() >= 900) // keep 900 or more
.map(s -> s.rep()) // keep just the name
.toList();
String team = Sale.ledger().stream()
.map(s -> s.rep())
.collect(Collectors.joining(", "));
String regions = Sale.ledger().stream()
.map(s -> s.region())
.distinct().sorted()
.collect(Collectors.joining(" / "));
Big sellers: [Emma, Jake, Sofia]
Team: Emma, Liam, Anna, Jake, Sofia, Mark
Regions: North / South / West
toList gives a List (a read-only one: bigSellers.add("Zoe") throws UnsupportedOperationException). Collectors.joining(", ") glues Strings into one, putting the separator only between names, so there's no comma after Mark. Any separator works. distinct keeps each region once and sorted orders them first.
Sort the sales into buckets
// 1. groupingBy: one List of sales per region
Map<String, List<Sale>> byRegion = Sale.ledger().stream()
.collect(Collectors.groupingBy(s -> s.region()));
System.out.println("In North: " + byRegion.get("North").size());
System.out.println("By region: " + byRegion);
// 2. counting(): how many sales in each region
Map<String, Long> counts = Sale.ledger().stream()
.collect(Collectors.groupingBy(s -> s.region(),
Collectors.counting()));
// 3. summingInt(): add up the amounts in each region
Map<String, Integer> totals = Sale.ledger().stream()
.collect(Collectors.groupingBy(s -> s.region(),
Collectors.summingInt(s -> s.amount())));
In North: 3
By region: {West=[Jake 1500], South=[Liam 800, Sofia 950], North=[Emma 1200, Anna 450, Mark 500]}
Counts: {West=1, South=2, North=3}
Totals: {West=1500, South=1750, North=2150}
groupingBy(s -> s.region()) makes the lambda's result the key and collects each region's sales into a List. Emma opens the North bucket; Anna finds it already there and joins her. A second collector changes what each bucket reports: counting() gives how many (as a Long), summingInt adds the amounts. groupingBy builds a HashMap, so the region order in the printout isn't promised.
Open the lists inside a list
// An order holds a List of items: a list inside a list
record Order(String customer, List<String> items) {}
List<Order> orders = List.of(
new Order("Sarah", List.of("Laptop", "Mouse")),
new Order("Chris", List.of("Monitor")),
new Order("Chloe", List.of("Mouse", "Keyboard", "Webcam")));
List<List<String>> nested =
orders.stream().map(o -> o.items()).toList();
List<String> items = orders.stream()
.flatMap(o -> o.items().stream()).toList();
List<String> toStock = items.stream().distinct().sorted().toList();
map: [[Laptop, Mouse], [Monitor], [Mouse, Keyboard, Webcam]]
flatMap: [Laptop, Mouse, Monitor, Mouse, Keyboard, Webcam]
To stock: [Keyboard, Laptop, Monitor, Mouse, Webcam]
map keeps the boxes: each order becomes its whole List, so you get a list of three lists. flatMap opens them: each List becomes a stream, and the six items pour into one flat stream, Mouse twice. Now it's a normal stream, so distinct drops the second Mouse and sorted goes A to Z.
The report, and when a loop is clearer
int total = Sale.ledger().stream()
.mapToInt(s -> s.amount()).sum();
// a running total changes every pass: a plain loop is clearer
int running = 0;
for (Map.Entry<String, Integer> e : byRegion.entrySet()) {
running += e.getValue(); // add this region's total
System.out.println(e.getKey() + " " + e.getValue()
+ ", running " + running);
}
Total: 5400
By region: {West=1500, South=1750, North=2150}
West 1500, running 1500
South 1750, running 3250
North 2150, running 5400
mapToInt turns each Sale into its int amount, and sum adds them: 5400. (Here byRegion is the summingInt map from before.) A stream handles each item on its own. A running total carries a value from pass to pass, so a plain loop is clearer.
Recap
| Want | Use |
|---|---|
| a List | toList() |
| one String | collect(Collectors.joining(", ")) |
| a Map of groups | groupingBy(key), plus counting() or summingInt(...) |
| one stream from many lists | flatMap(o -> o.items().stream()) |
| a sum of a field | mapToInt(...).sum() |
Pick the container, and let collect fill it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Lambdas and Functional Interfaces
A six-line anonymous Discount becomes total -> total * 0.85. Lambdas with no, one and two parameters show which brackets and braces can go, a Runnable job runs between START and DONE, and two Comparator lambdas sort students by marks, then by name.
Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
Four ready-made sockets for lambdas: Predicate tests 20 >= 18, Function turns 5 into 15, Consumer prints Hello, Priya, Supplier hands back Monday. Then isPositive.and(isEven), isEven.negate() and multiply.andThen(addFive), which turns 3 and 4 into 17.
Java Optional: Saying Maybe Without null
A phone book returns null for Omar and the next .length() crashes. Optional.ofNullable gives a box instead: Optional[555-1234] or Optional.empty. orElse hands over "no number", ifPresent runs only for Asha, and map adds +1 only when there's a number.
Java Streams I: filter, map and reduce
Picture a conveyor belt: 4, 7, 2, 9, 5 ride through filter(n -> n > 4) and map(n -> n * 10) and come out as [70, 90, 50]. Then sorted and count on exam scores, and reduce folding a cart of 499, 1299, 250 and 799 into a 2847 bill.
