Java Streams
The Stream API (java.util.stream) provides a functional way to process sequences of elements from collections, supporting operations like filter, map, sorted, and collect in a readable pipeline.
Streams are not data structures themselves โ they describe a computation to perform on a source of data, and are typically used once.
list.stream()
.filter(x -> condition)
.map(x -> transform)
.collect(Collectors.toList());Building a stream pipeline
Get a stream from a collection with .stream(), apply intermediate operations like filter() and map(), then a terminal operation like collect() or forEach() to produce a result.
Common stream operations
filter() keeps elements matching a condition, map() transforms elements, sorted() orders them, and collect(Collectors.toList()) gathers results back into a List.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5);
List<Integer> evenSquares = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(evenSquares);
}
}[4, 16]The stream filters even numbers, squares them, then collects the results into a List.
Key points
- Streams describe a pipeline of operations on data, not a data structure.
- filter() selects elements; map() transforms them.
- Terminal operations like collect() or forEach() produce a final result.
- Streams work naturally with lambda expressions.
