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

  1. Start with Values 1 and 2 in the same group
  2. Do this Group and add
  3. Result 3
Both values contribute to the same group's total.

Apply it to a real problem

  1. Start with Paid orders for Ali and Mei
  2. Do this Exclude unpaid orders and total items by customer
  3. Result Ali 1, Mei 6
The unpaid five-item order does not contribute to Ali's total.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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);
    }
}
Output
{Ali=1, Mei=6}

Official Java documentation