What are the main features of the Java 8 Stream API?
The Stream API, introduced in Java 8 in `java.util.stream`, enables functional-style processing of sequences of elements through declarative, composable pipelines. A stream is not a data structure — it does not store data. It conveys elements from a source (collection, array, generator function, I/O channel) through a pipeline of operations.
A stream pipeline has three parts: 1. **Source**: `collection.stream()`, `Arrays.stream(arr)`, `Stream.of(...)`, `Stream.generate(supplier)`, `Stream.iterate(seed, function)`. 2. **Intermediate operations**: lazy — they return a new stream and are not executed until a terminal operation is called. Examples: `filter(predicate)`, `map(function)`, `flatMap(function)`, `distinct()`, `sorted()`, `limit(n)`, `peek(consumer)`. 3. **Terminal operations**: trigger the pipeline to execute. Examples: `collect(collector)`, `forEach(consumer)`, `reduce(identity, accumulator)`, `count()`, `findFirst()`, `anyMatch(predicate)`, `toList()` (Java 16).
Laziness is a key design feature. Intermediate operations are fused; the stream processes elements one at a time through the entire pipeline rather than creating intermediate collections. This enables short-circuit operations like `findFirst()` to stop processing as soon as a match is found.
Parallel streams (`collection.parallelStream()`) distribute work across the ForkJoinPool's common pool. They are useful for CPU-bound operations on large datasets but counterproductive for small collections or I/O-bound tasks due to thread management overhead and potential race conditions with non-thread-safe collectors.
`Collectors` provides rich terminal operations: `toList()`, `toSet()`, `groupingBy()`, `partitioningBy()`, `joining()`, `counting()`, and more. `Collectors.groupingBy()` is one of the most powerful — it produces a `Map<K, List<V>>` grouping elements by a classifier function.
Streams are consumed once — reusing a stream after a terminal operation throws `IllegalStateException`.
Explains the source-intermediate-terminal pipeline structure, names key operations in each category, and describes lazy evaluation.
Also covers parallel streams with their use cases and caveats, Collectors API breadth, the one-use constraint on streams, and flatMap for flattening nested structures.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment