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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The classifier function of groupingBy determines the map's keys, one bucket per distinct value.
- 2A downstream collector transforms each group from a raw list into a count, sum, or projected list.
- 3A supplier argument lets you control the concrete map type, such as a sorted TreeMap.
Related explainers
java
@Service public class PaymentGatewayClient { private static final Logger log = LoggerFactory.getLogger(PaymentGatewayClient.class);
Resilient payment calls with Spring Retry
retry
backoff
fault-tolerance
Intermediate
7 steps
java
public final class Debouncer<T> { private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
How a debouncer collapses bursts in Java
debounce
concurrency
scheduling
Intermediate
9 steps
java
package com.example.logs; import java.io.IOException; import java.io.UncheckedIOException;
Counting HTTP statuses with Java streams
streams
regex
file-io
Intermediate
6 steps
typescript
interface Order { id: number; customerId: string; total: number;
A type-safe groupBy in TypeScript
generics
reduce
type-inference
Intermediate
6 steps
java
@Service public class GitHubClient { private final WebClient webClient;
Calling the GitHub API with Spring WebClient
reactive
http-client
dependency-injection
Intermediate
7 steps
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 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/grouping-streams-with-java-collectors-explained-java-f1e0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.