Java ยท Chapter 40 of 42

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.

Syntax
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.

Example 1 (java)
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);
  }
}
Output
[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.
๐Ÿ’ก Note: Streams are typically consumed once โ€” you cannot reuse the same stream after a terminal operation runs.

๐Ÿ“ Quick Quiz

1. What does filter() do in a stream?

2. What kind of operation is collect()?

3. Can a stream be reused after a terminal operation?