Part 09 / Topic 8 of 10
The Streams API
A stream is a pipeline over a source of data (usually a collection): zero or more intermediate operations (filter, map, sorted, distinct) that each return a new stream, ending in exactly one terminal operation (collect, toList, forEach, reduce, count, findFirst) that actually produces a result. A stream never modifies its source and can only be used once.
Real-world example: a shop's orders, filtered, sorted and summarised.
List<String> pendingIdsBySizeDesc = orders.stream()
.filter(o -> o.status().equals("PENDING"))
.sorted((a, b) -> Double.compare(b.amount(), a.amount()))
.map(Order::id)
.toList();
pending orders, biggest first: [ORD-1003, ORD-1002]
Collecting results with Collectors
.toList() (Java 16+) covers the common case. For anything richer — joining into text, grouping, counting — use .collect(...) with a Collectors factory method:
String allCities = orders.stream().map(Order::city).distinct().sorted()
.collect(Collectors.joining(", ", "[", "]"));
// cities visited: [Chennai, Delhi, Pune]
Map<String, Double> amountByCity = orders.stream()
.collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.summingDouble(Order::amount)));
// total amount by city: {Chennai=350.0, Delhi=2299.0, Pune=8698.0}
Map<String, Long> countByStatus = orders.stream()
.collect(Collectors.groupingBy(Order::status, TreeMap::new, Collectors.counting()));
// order count by status: {CANCELLED=1, DELIVERED=3, PENDING=2}
groupingBy(classifier, mapFactory, downstream) groups by classifier, puts the groups in whatever Map mapFactory makes (here TreeMap::new, so the keys come out sorted), and reduces each group with downstream (summingDouble, counting, averagingDouble, or plain toList()). partitioningBy is the same idea specialised for exactly two groups, keyed by true/false:
Map<Boolean, List<String>> bigVsSmall = orders.stream()
.collect(Collectors.partitioningBy(o -> o.amount() >= 1000,
Collectors.mapping(Order::id, Collectors.toList())));
amount >= 1000: [ORD-1001, ORD-1002, ORD-1003]
amount < 1000: [ORD-1004, ORD-1005, ORD-1006]
.reduce(identity, accumulator) folds every element down to one value, the same shape as Collectors.summingDouble but general-purpose:
double grandTotal = orders.stream().map(Order::amount).reduce(0.0, Double::sum); // 11347.0
anyMatch/allMatch/count answer yes/no/how-many questions directly, without collecting anything:
any cancelled order? true
all delivered? false
how many Pune orders? 3
Streams are lazy
Nothing in a stream pipeline runs until a terminal operation is called. Intermediate operations just build up a plan.
var pipeline = orders.stream().map(o -> { mapCalls.incrementAndGet(); return o.id(); });
System.out.println("map calls before any terminal operation: " + mapCalls.get()); // 0
List<String> ids = pipeline.toList(); // NOW the pipeline runs
System.out.println("map calls = " + mapCalls.get()); // 6
Laziness also lets a stream stop early. findFirst() after a filter does not look at every element — it stops the moment it finds a match:
String firstPune = orders.stream()
.peek(o -> looked.incrementAndGet())
.filter(o -> o.city().equals("Pune"))
.map(Order::id)
.findFirst().orElseThrow();
first Pune order: ORD-1001, orders looked at: 1 of 6
peek is for exactly this kind of debugging/counting — never use it to do real work, since whether it even runs on every element depends on what comes after it in the pipeline (as this example itself shows).
Full program: examples/StreamBasics.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.