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
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
php
<?php namespace App\Services\Reports;
Streaming a monthly revenue CSV in Laravel
csv-export
lazy-collections
eloquent-query
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/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.