java 30 lines · 5 steps

Grouping streams with Java Collectors

Four flavors of Collectors.groupingBy show how downstream collectors reshape each group.

Explained by highlit
1public Map<Long, List<Order>> ordersByCustomer(List<Order> orders) {
2 return orders.stream()
3 .collect(Collectors.groupingBy(Order::getCustomerId));
4}
5 
6public Map<Long, BigDecimal> totalSpentByCustomer(List<Order> orders) {
7 return orders.stream()
8 .filter(Order::isPaid)
9 .collect(Collectors.groupingBy(
10 Order::getCustomerId,
11 Collectors.reducing(
12 BigDecimal.ZERO,
13 Order::getTotal,
14 BigDecimal::add)));
15}
16 
17public Map<Long, Long> orderCountByCustomer(List<Order> orders) {
18 return orders.stream()
19 .collect(Collectors.groupingBy(
20 Order::getCustomerId,
21 TreeMap::new,
22 Collectors.counting()));
23}
24 
25public Map<OrderStatus, List<String>> orderNumbersByStatus(List<Order> orders) {
26 return orders.stream()
27 .collect(Collectors.groupingBy(
28 Order::getStatus,
29 Collectors.mapping(Order::getOrderNumber, Collectors.toList())));
30}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The classifier function of groupingBy determines the map's keys, one bucket per distinct value.
  2. 2A downstream collector transforms each group from a raw list into a count, sum, or projected list.
  3. 3A supplier argument lets you control the concrete map type, such as a sorted TreeMap.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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