Streams & Lambdas
Functional programming in Java — lambdas, functional interfaces, method references, the Stream API (map, filter, reduce, collect, groupingBy), laziness, parallel streams, and Optional.
Java 8 added lambdas (anonymous functions) and the Stream API (declarative pipelines over collections). Together they replace many verbose loops with readable transformations.
Lambdas and functional interfaces
A lambda is a concise implementation of a functional interface — an interface with exactly one abstract method.
// Before: anonymous class
Comparator<String> byLength = new Comparator<>() {
public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};
// Lambda
Comparator<String> byLength2 = (a, b) -> Integer.compare(a.length(), b.length());
// Even better: a comparator factory with a method reference
Comparator<String> byLength3 = Comparator.comparingInt(String::length);The core functional interfaces (java.util.function)
| Interface | Signature | Example |
|---|---|---|
Function<T, R> | R apply(T) | String::length |
BiFunction<T, U, R> | R apply(T, U) | (a, b) -> a + b |
Predicate<T> | boolean test(T) | s -> s.isEmpty() |
Consumer<T> | void accept(T) | System.out::println |
Supplier<T> | T get() | ArrayList::new |
UnaryOperator<T> / BinaryOperator<T> | T apply(T) / T apply(T, T) | String::trim, Integer::sum |
| Primitive versions | IntFunction, ToIntFunction, IntPredicate… | Avoid boxing |
Functions compose: f.andThen(g), f.compose(g), p.and(q), p.negate(), comparator.thenComparing(...).
Method references
| Kind | Syntax | Equivalent lambda |
|---|---|---|
| Static method | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object | System.out::println | x -> System.out.println(x) |
| Instance method of an arbitrary object | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
Capturing variables
Lambdas can use local variables only if they're effectively final (never reassigned). This avoids data races on stack variables. To accumulate, use streams' reductions or an AtomicInteger, not a captured counter.
The Stream API
A stream is a pipeline: a source, zero or more intermediate operations (lazy, return a new stream) and one terminal operation (triggers processing and produces a result).
record Order(String customer, String status, long totalCents, List<String> items) {}
long paidRevenue = orders.stream()
.filter(o -> o.status().equals("PAID"))
.mapToLong(Order::totalCents)
.sum();
List<String> topCustomers = orders.stream()
.sorted(Comparator.comparingLong(Order::totalCents).reversed())
.map(Order::customer)
.distinct()
.limit(3)
.toList(); // Java 16+: unmodifiable list
List<String> allItems = orders.stream()
.flatMap(o -> o.items().stream()) // one-to-many
.toList();
boolean anyLarge = orders.stream().anyMatch(o -> o.totalCents() > 100_000);
Optional<Order> first = orders.stream().filter(o -> o.status().equals("NEW")).findFirst();Common operations
| Intermediate | Terminal |
|---|---|
filter, map, flatMap, mapToInt | collect, toList, forEach |
distinct, sorted, limit, skip | reduce, count, sum, min, max, average |
peek (debugging), takeWhile, dropWhile | anyMatch, allMatch, noneMatch |
boxed, mapMulti | findFirst, findAny, toArray |
Collectors
import static java.util.stream.Collectors.*;
Map<String, List<Order>> byCustomer = orders.stream().collect(groupingBy(Order::customer));
Map<String, Long> revenueByCustomer = orders.stream()
.collect(groupingBy(Order::customer, summingLong(Order::totalCents)));
Map<String, Long> countByStatus = orders.stream()
.collect(groupingBy(Order::status, TreeMap::new, counting())); // sorted map
Map<Boolean, List<Order>> bigAndSmall = orders.stream()
.collect(partitioningBy(o -> o.totalCents() > 10_000));
Map<String, Order> byId = orders.stream()
.collect(toMap(Order::customer, o -> o, (a, b) -> a)); // merge fn handles duplicate keys
String csv = names.stream().collect(joining(", ", "[", "]"));
LongSummaryStatistics stats = orders.stream().collect(summarizingLong(Order::totalCents));Laziness and short-circuiting
Nothing happens until the terminal operation runs. Elements then flow through the pipeline one at a time (vertically), not stage by stage:
Stream.of("a", "bb", "ccc", "dddd")
.filter(s -> { System.out.println("filter " + s); return s.length() > 1; })
.map(s -> { System.out.println("map " + s); return s.toUpperCase(); })
.findFirst();
// filter a, filter bb, map bb — then stops: "ccc" and "dddd" are never touchedThis allows infinite streams (Stream.iterate, Stream.generate) with limit or takeWhile.
Rules and pitfalls
- A stream can be consumed only once.
- Operations must be non-interfering (don't modify the source) and preferably stateless and side-effect-free. Don't
forEach(list::add)into an external list —collectinstead. - Use primitive streams (
IntStream,mapToLong) to avoid boxing in hot paths. - Debugging long chains is harder; keep them short and well named. A plain loop is fine when clearer.
- Checked exceptions don't fit lambdas; wrap them or use a helper.
Parallel streams
.parallel() splits work across the common ForkJoinPool. It can help for large, CPU-bound, independent workloads over splittable sources (arrays, ArrayList, ranges). It often hurts for small data, I/O-bound work (blocks the shared pool), LinkedList/iterator sources, or operations requiring order (findFirst, sorted, limit). Measure before using it.
Optional
Optional<User> user = repo.findById(id);
String city = user.map(User::address)
.map(Address::city)
.filter(c -> !c.isBlank())
.orElse("Unknown");
user.ifPresentOrElse(this::greet, () -> log.info("no user"));
User u = user.orElseThrow(); // NoSuchElementException if empty
User v = user.orElseGet(this::createGuest); // lazily computed fallback (orElse always evaluates its argument)Avoid optional.get() without checking, Optional fields or parameters, and Optional<List<T>> (return an empty list).
- Lambdas implement functional interfaces; method references are shorthand for simple lambdas.
- Streams: source → lazy intermediate operations → one terminal operation.
- Collectors (groupingBy, partitioningBy, toMap, joining) replace most aggregation loops.
- Streams are single-use, lazy and short-circuiting; keep operations side-effect free.
- Parallel streams only for large CPU-bound work — measure.
- Optional models absence in return values; chain map/filter/orElse.
QWhat is the difference between map and flatMap?easy
map transforms each element into exactly one element (Stream of T to Stream of R). flatMap transforms each element into a stream and flattens all those streams into one, so one input can yield zero or many outputs — for example, turning a stream of orders into a stream of all their items.
QWhy are streams lazy and why does it matter?medium
Intermediate operations only build the pipeline; work happens when a terminal operation pulls elements through it one at a time. This enables short-circuiting (findFirst stops early), fusing operations into a single pass, and working with infinite streams, and it avoids building intermediate collections.