Introduction
Much code consists of loops that filter, transform and summarise collections. Since Java 8, the same work can be written as a stream pipeline that says what to compute rather than how to loop, and behaviour such as "how to compare" or "which items to keep" can be passed around as a lambda. Modern Java code uses both constantly.
How it works
A lambda is a short function: parameters, an arrow and an expression or block. x -> x * 2 doubles a number; (a, b) -> a.length() - b.length() compares strings by length. A lambda can be used wherever a functional interface is expected, an interface with one abstract method: Comparator<T>, Predicate<T> (a test), Function<T, R> (a conversion), Consumer<T> (an action) and Supplier<T>. A method reference such as String::length or Sale::rep is shorthand for a lambda that just calls one method.
Comparators are the everyday use: list.sort(...) with Comparator.comparing(Person::age), then .reversed() for descending, or .thenComparing(Person::name) for ties.
A stream processes a collection's values in a pipeline:
List<String> names = people.stream() // source
.filter(p -> p.age() >= 18) // keep adults
.map(Person::name) // turn each into its name
.sorted() // sort
.collect(Collectors.toList()); // gather the result
Intermediate operations such as filter, map, sorted, distinct and limit return a new stream and do nothing until a terminal operation such as collect, count, forEach, sum or findFirst runs. A stream can be used only once, and it never changes its source collection.
For numbers, mapToInt gives an IntStream with sum, average and max. Collectors gather results: toList, joining(", "), groupingBy(key) to make a map of lists, groupingBy(key, counting()) or summingInt(...) to summarise each group, and partitioningBy(test) to split in two.
Operations that may find nothing, such as findFirst, max and average, return an Optional: use orElse(default), isPresent() or ifPresent(...) instead of risking null.
Use streams for data transformations; a plain loop is still clearer when the logic has many steps or needs early exits.
Example
import java.util.*;
import java.util.stream.*;
public class Main {
record Sale(String rep, String region, int amount) {}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("Rina", "North", 500),
new Sale("Arif", "South", 300),
new Sale("Zoya", "North", 700),
new Sale("Omar", "South", 450));
// A pipeline: keep big sales, take the rep's name, sort, collect.
List<String> big = sales.stream()
.filter(s -> s.amount() >= 450)
.map(Sale::rep)
.sorted()
.collect(Collectors.toList());
System.out.println(big);
int total = sales.stream().mapToInt(Sale::amount).sum();
System.out.println("total " + total);
Map<String, Integer> byRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.summingInt(Sale::amount)));
System.out.println(byRegion);
Sale best = Collections.max(sales, Comparator.comparingInt(Sale::amount));
System.out.println("best " + best.rep());
}
}Line by line
Saleis a record; the list holds four sales.- The first pipeline keeps sales of at least 450, maps them to the rep's name, sorts and collects.
mapToInt(...).sum()adds the amounts.groupingBywith aTreeMapandsummingInttotals the amounts per region, sorted by region.Collections.maxwithComparator.comparingIntfinds the biggest sale.
Expected result
[Omar, Rina, Zoya]
total 1950
{North=1200, South=750}
best Zoya
In the real world
Streams and lambdas appear throughout modern Java: reports built with grouping collectors, event handlers passed as lambdas, sorting by several keys with comparators, and frameworks such as Spring that take lambdas for configuration. Reading a pipeline from top to bottom as a list of steps is a key skill.
Common mistakes
- Reusing a stream after a terminal operation, which throws IllegalStateException.
- Changing outside variables inside a lambda; captured local variables must be effectively final.
- Calling get() on an empty Optional; use orElse or check first.
- Forcing complex logic into one long pipeline when a loop would be clearer.
Best practices
- Prefer method references when a lambda only calls one method.
- Keep each pipeline step simple, one operation per line.
- Use Comparator.comparing with thenComparing for multi-key sorting.
Summary
Lambdas and method references implement functional interfaces such as Comparator, Predicate and Function, so behaviour can be passed as a value. Streams process collections in pipelines of intermediate operations ended by a terminal one, Collectors group and summarise results, and Optional represents a result that may be missing.
Quick check
Key takeaways
- Lambdas and method references pass behaviour, such as a comparison or a test, as a value.
- Streams describe what to compute: filter, map and sort, then collect the result.
- Collectors.groupingBy summarises by key; Optional makes "no result" explicit.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.