Sobes.tech
Junior — Middle

Explain the working principle of the pipeline method in Stream and its features.

sobes.tech AI

Answer from AI

A pipeline method in Java Stream API represents a chain of intermediate operations (for example, filter, map) that return a new Stream, and is terminated by a terminal operation (for example, collect, forEach). Intermediate operations are lazy — they are not executed immediately but are accumulated in the pipeline. Execution occurs only when a terminal operation is invoked, which initiates a traversal of the data and applies all operations sequentially.

Features:

  • Laziness: operations are not performed until the terminal operation.
  • Optimization potential: Stream can combine operations to improve performance.
  • Immutability: the original Stream is not modified; each operation returns a new Stream.

Example:

List<String> result = list.stream()
    .filter(s -> s.startsWith("A"))
    .map(String::toUpperCase)
    .collect(Collectors.toList());