Course contentsShow
← Java
Lesson 1399 of 2,87031. Streams API: Creation and BasicsFree lesson

Building Pipelines: Chaining Intermediate Operations

Practice constructing multi-stage pipelines by chaining filter, map, and other intermediate operations together.

Building Pipelines: Chaining Intermediate Operations

You'll learn how to construct fluent, multi-stage stream pipelines by linking intermediate operations together.

The Power of Method Chaining

Since intermediate operations return new streams, you can chain them together in a single fluent expression. Each operation transforms the stream and passes it to the next, creating a pipeline that describes what you want to do with your data declaratively.

Think of it like an assembly line: raw materials enter, pass through multiple workstations (filter, map, etc.), and finally reach the end where a terminal operation produces the result.

Building Multi-Stage Pipelines

Here's how intermediate operations chain together:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");

List<String> result = names.stream()
    .filter(name -> name.length() > 3)      // Keep names longer than 3 chars
    .map(String::toUpperCase)                // Convert to uppercase
    .filter(name -> name.startsWith("C"))    // Keep only those starting with 'C'
    .collect(Collectors.toList());           // Terminal operation

System.out.println(result); // [CHARLIE]

Each intermediate operation:

  • Receives a stream from the previous step
  • Performs its transformation
  • Returns a new stream for the next step
  • Doesn't execute until the terminal operation runs

More Complex Example

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

int sum = numbers.stream()
    .filter(n -> n % 2 == 0)     // Keep even numbers: [2, 4, 6]
    .map(n -> n * n)             // Square them: [4, 16, 36]
    .filter(n -> n > 10)         // Keep those > 10: [16, 36]
    .reduce(0, Integer::sum);    // Terminal: sum them up

System.out.println(sum); // 52

The beauty is readability: you describe what transformations you want without loops or temporary collections.

Key Takeaway: Stream pipelines let you chain intermediate operations (filter, map, etc.) in sequence, creating readable, declarative data transformations that execute lazily when a terminal operation is called.