Programs & Examples
Streams API · Study material
An e-commerce sales report with streams
Filtering refunds, totalling revenue, grouping by category, ranking customers and finding the largest order – each in one pipeline.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
record Txn(String id, String customer, String category, double amount, boolean refunded) { }
public class Main {
public static void main(String[] args) {
List<Txn> txns = List.of(
new Txn("T1", "Asha", "Books", 499, false), new Txn("T2", "Ravi", "Electronics", 15999, false),
new Txn("T3", "Asha", "Electronics", 2499, true), new Txn("T4", "Meena", "Books", 899, false),
new Txn("T5", "Ravi", "Fashion", 1999, false), new Txn("T6", "Asha", "Fashion", 3499, false),
new Txn("T7", "John", "Books", 299, false));
List<Txn> valid = txns.stream().filter(t -> !t.refunded()).toList();
System.out.printf("revenue %.2f from %d orders (%d refunded)%n", valid.stream().mapToDouble(Txn::amount).sum(), valid.size(), txns.size() - valid.size());
Map<String, Double> byCategory = valid.stream().collect(Collectors.groupingBy(Txn::category, TreeMap::new, Collectors.summingDouble(Txn::amount)));
byCategory.forEach((c, a) -> System.out.printf(" %-12s %9.2f%n", c, a));
String topCustomers = valid.stream()
.collect(Collectors.groupingBy(Txn::customer, Collectors.summingDouble(Txn::amount)))
.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.limit(2)
.map(e -> e.getKey() + "(" + e.getValue().intValue() + ")")
.collect(Collectors.joining(", "));
System.out.println("top customers: " + topCustomers);
System.out.println("largest order: " + valid.stream().max(Comparator.comparingDouble(Txn::amount)).map(Txn::id).orElse("-"));
}
}
revenue 23194.00 from 6 orders (1 refunded) Books 1697.00 Electronics 15999.00 Fashion 5498.00 top customers: Ravi(17998), Asha(3998) largest order: T2
Grouping and partitioning employees
The Collectors example counts, averages and lists employees by department and splits them by age.
Laziness made visible
The laziness example uses peek to show that elements flow one at a time and that findFirst stops early.