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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.