# Streams API: Pipelines, Laziness and Collectors

> Explain the Java Streams API. What are intermediate and terminal operations, why are streams lazy, and how do map, flatMap, reduce and groupingBy work?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-streams-api
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

Explain the Java Streams API. What are intermediate and terminal operations, why are streams lazy, and how do map, flatMap, reduce and groupingBy work?

## Answer

A stream is not a data structure. That is the first sentence I want you to remember, because it clears up most confusion. A stream is a pipeline for processing a sequence of elements from a source (a collection, array, file or generator) using a chain of operations, in a declarative style: you describe what you want, not how to loop. It does not store elements and it does not modify the source.

Every pipeline has three parts. A source (list.stream(), Arrays.stream, Stream.of, IntStream.range), zero or more intermediate operations, and exactly one terminal operation. Intermediate operations return another stream and are lazy: filter, map, flatMap, sorted, distinct, limit, skip and peek. Terminal operations trigger execution and produce a result or side effect: collect, forEach, reduce, count, sum, min, max, findFirst, anyMatch, allMatch and toList (Java 16).

Laziness matters. Nothing runs until the terminal operation is called. Elements are then pulled through the pipeline one at a time, vertically: each element goes through filter, then map, and so on before the next element starts. This makes short-circuiting operations like findFirst, anyMatch and limit efficient: on an infinite stream, limit(5) stops after five elements. Stateful operations such as sorted must see all elements before passing any along.

Streams are single-use. Once a terminal operation has run, reusing the stream throws IllegalStateException with the message stream has already been operated upon or closed. If you need to reuse a pipeline, create a new stream, or use a Supplier of streams.

Now the operations people mix up. map transforms each element one-to-one. flatMap transforms each element into a stream and flattens all those streams into one, so use it for a list of lists or splitting sentences into words. reduce folds elements into one value, like sum with an identity and an accumulator. Collectors provide rich terminal collection: toList, toSet, toMap (throws on duplicate keys unless you pass a merge function), joining, counting, summingInt, averagingDouble, partitioningBy (a Map of true and false) and groupingBy, which builds a Map from a classifier and can take a downstream collector, for example groupingBy(String::length, counting()).

For primitives, use IntStream, LongStream and DoubleStream to avoid boxing; they add sum, average and summaryStatistics, and you convert with mapToInt or boxed.

Parallel streams (parallelStream or .parallel()) split work across the common ForkJoinPool. They help only for large data sets and CPU-heavy, stateless, non-blocking operations. They can be slower for small data, and are dangerous with shared mutable state or blocking calls since they compete for the common pool. Also avoid side effects in lambdas and never modify the source collection during a stream.

Two more details for interviews: peek is meant for debugging, not for logic; and a stream's toList returns an unmodifiable list while Collectors.toList makes no guarantee about mutability. Bring up the fact that findFirst respects encounter order while findAny is free on parallel streams.

## Code examples

### A typical pipeline and groupingBy

```
import java.util.*;
import java.util.stream.*;

public class StreamDemo {
    public static void main(String[] args) {
        List<String> names = List.of("Asha", "Ravi", "Neha", "Karan", "Amit");

        List<String> aNames = names.stream()
            .filter(n -> n.startsWith("A"))
            .map(String::toUpperCase)
            .sorted()
            .toList();
        System.out.println(aNames);

        Map<Integer, Long> byLength = names.stream()
            .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
        System.out.println(byLength);

        System.out.println(IntStream.rangeClosed(1, 5).sum());

        List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(4, 5));
        System.out.println(nested.stream().flatMap(List::stream).map(x -> x * x).toList());
    }
}
```

Four names have length 4 and one has length 5. flatMap flattens the nested lists before squaring.

### Laziness and short-circuiting

```
import java.util.stream.*;

public class LazyDemo {
    public static void main(String[] args) {
        var result = Stream.of(1, 2, 3, 4)
            .peek(x -> System.out.println("peek " + x))
            .filter(x -> x > 2)
            .findFirst();
        System.out.println(result);
    }
}
```

Elements flow one at a time and findFirst stops as soon as 3 passes the filter, so 4 is never processed.

## Key points

- A stream is a pipeline, not storage, and it never modifies its source.
- Intermediate operations are lazy; the terminal operation triggers execution.
- Streams are single-use.
- map is one-to-one, flatMap flattens one-to-many.
- Use parallel streams only for large, CPU-bound, stateless work.

## Common follow-up questions

- Difference between map and flatMap?
- What happens if you reuse a stream?
- When should you avoid parallel streams?
- How does Collectors.toMap behave with duplicate keys?

## Interview tips

- Demonstrate laziness with the peek and findFirst example; it proves you understand how execution works.
- Mention primitive streams to avoid boxing overhead.

## Concepts covered

Streams, Intermediate vs Terminal, Lazy Evaluation, Collectors, map vs flatMap

Previous: [Lambdas, Functional Interfaces and Method References](https://www.internhack.in/learn/interview/java-interview/java-lambdas-functional-interfaces) · Next: [Optional: Purpose, Usage and Anti-Patterns](https://www.internhack.in/learn/interview/java-interview/java-optional) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Records in Java: Concise Immutable Data Carriers](https://www.internhack.in/learn/interview/java-interview/java-records)
- [Tricky Output Questions: Types, Overflow and Overloading](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-basics)
- [Tricky Output: finally Overrides and Initialization Order](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-finally-init-order)
- [JDK vs JRE vs JVM and Platform Independence](https://www.internhack.in/learn/interview/java-interview/java-jdk-jre-jvm)
- [String Immutability and the String Pool](https://www.internhack.in/learn/interview/java-interview/java-string-immutability-pool)
- [String vs StringBuilder vs StringBuffer](https://www.internhack.in/learn/interview/java-interview/java-string-stringbuilder-stringbuffer)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
