Group successful orders by customer in Java
Filter failed orders before grouping. A TreeMap produces a predictable customer order and summingInt reduces each group to its total item count.
A simple example
Group and add
- Start with Values 1 and 2 in the same group
- Do this Group and add
- Result 3
Apply it to a real problem
- Start with Paid orders for Ali and Mei
- Do this Exclude unpaid orders and total items by customer
- Result Ali 1, Mei 6
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) throws Exception {
record Order(String customer, int items, boolean paid) {}
var orders = List.of(new Order("Mei", 2, true), new Order("Ali", 1, true),
new Order("Mei", 4, true), new Order("Ali", 5, false));
var totals = orders.stream().filter(Order::paid)
.collect(Collectors.groupingBy(Order::customer, TreeMap::new,
Collectors.summingInt(Order::items)));
System.out.println(totals);
}
}
{Ali=1, Mei=6}