Java streams and lambdas: filter, map, collect and groupingBy
Lambdas and method references, the stream pipeline, collecting into lists and maps, groupingBy for reports, Optional, and when a plain loop is clearer.
Streams let you describe what to do with a collection (keep these, transform those, group by that) instead of writing the loop by hand. They're built on lambdas, so start there.
Lambdas and method references
A lambda is a short anonymous function. It can be used wherever an interface with a single abstract method (a functional interface) is expected:
Comparator<Flight> byDeparture = (a, b) -> a.departure().compareTo(b.departure());
Comparator<Flight> same = Comparator.comparing(Flight::departure); // method reference
Predicate<Flight> delayed = f -> f.delayMinutes() > 15;Function<T, R>, Predicate<T>, Supplier<T> and Consumer<T> cover most needs.
A pipeline: source, operations, result
List<String> late = flights.stream() // source
.filter(f -> f.delayMinutes() > 15) // intermediate
.sorted(Comparator.comparing(Flight::departure)) // intermediate
.map(Flight::number) // intermediate
.collect(Collectors.toList()); // terminalIntermediate operations are lazy: nothing runs until the terminal operation. (toList()
without collect arrived in Java 16; on Java 11 use Collectors.toList().)
Reports with groupingBy
Map<String, Long> flightsPerGate = flights.stream()
.collect(Collectors.groupingBy(Flight::gate, Collectors.counting()));
Map<String, Double> avgDelayByAirline = flights.stream()
.collect(Collectors.groupingBy(Flight::airline,
Collectors.averagingInt(Flight::delayMinutes)));
Map<Boolean, List<Flight>> onTime = flights.stream()
.collect(Collectors.partitioningBy(f -> f.delayMinutes() <= 15));Need a sorted report? Collect into a TreeMap:
groupingBy(Flight::gate, TreeMap::new, counting()).
Optional: an explicit "maybe"
findFirst, max and min return Optional, because there might be no result:
String next = flights.stream()
.filter(f -> f.gate().equals("B4"))
.min(Comparator.comparing(Flight::departure))
.map(Flight::number)
.orElse("none");Use orElse, orElseGet or orElseThrow; avoid get() without checking.
Primitive streams
IntStream, LongStream and DoubleStream avoid boxing and add sum, average and range:
int seats = flights.stream().mapToInt(Flight::seatsSold).sum();
IntStream.rangeClosed(1, 5).forEach(i -> System.out.println("Gate " + i));When a loop is clearer
- You need an early
returnorbreakwith complex conditions. - You update several variables at once.
- You need checked exceptions inside the lambda (they don't propagate out of lambdas).
Common mistakes
- Side effects in
maporfilter(modifying outside lists). - Reusing a stream after its terminal operation.
parallel()on small or I/O-bound work: overhead, no gain.
Streams are used throughout Java Intermediate and Java Advanced.
Questions and answers
- Are Java streams faster than for loops?
- Not usually; for simple work a loop is as fast or faster. Streams win on readability for transform-filter-collect pipelines. Parallel streams can help for large CPU-bound work, but measure before using them.
- Can I reuse a Java stream?
- No. A stream can be consumed only once; a second terminal operation throws IllegalStateException. Create a new stream from the source each time.
Practise it
Read next
- Java collections: choosing between List, Set, Map and Deque
ArrayList vs LinkedList, HashMap vs TreeMap, HashSet vs LinkedHashSet, ArrayDeque for stacks and queues: what each costs and which to reach for first.
- Java interfaces vs abstract classes: when to use which
What interfaces and abstract classes are each for, default methods, composition over inheritance, and how interfaces make Java code easy to test.