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

Intermediate Operations Return New Streams

Discover how operations like filter, map, and sorted return Stream objects enabling method chaining.

Intermediate Operations Return New Streams

You'll learn why intermediate operations are chainable and how they build processing pipelines without modifying the original stream.

The Core Idea

When you apply an intermediate operation like filter(), map(), or sorted() to a stream, you don't modify the original stream. Instead, you get back a brand new Stream object. This is the secret behind method chaining: each operation returns a stream that you can immediately call another operation on.

Think of it like a conveyor belt in a factory. Each intermediate operation adds a new processing station to the belt, but the belt itself keeps moving forward. Each station returns a new version of the belt with an additional processing step attached.

Why This Matters

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

Stream<String> stream1 = names.stream();
Stream<String> stream2 = stream1.filter(s -> s.length() > 3);
Stream<String> stream3 = stream2.map(String::toUpperCase);

Notice that stream1, stream2, and stream3 are three different objects. The filter() operation doesn't change stream1—it returns a new stream (stream2) that remembers to filter. Similarly, map() returns yet another new stream (stream3).

Method Chaining in Action

Because each intermediate operation returns a Stream, you can chain them fluently:

names.stream()
     .filter(s -> s.length() > 3)
     .map(String::toUpperCase)
     .sorted();  // Also returns a new Stream

Each operation is a step in a pipeline. None execute immediately—they just build up a plan that will run when a terminal operation is called.

Key Takeaway:
Intermediate operations return new Stream objects rather than modifying existing ones, enabling fluent method chaining and lazy pipeline construction.