Top 5 Streams Interview Questions
Browse 5 real-world technical and behavioral interview questions about Streams. Review scenarios, edge cases, and architectural best practices.
Your Collectors.toMap call passed every test and threw in production. What did the code assume, and what are your options?
It assumed unique keys and non-null values. Collectors.toMap throws IllegalStateException on a duplicate key and NullPointerException on a null value, so supply a merge function that encodes a real rule, use groupingBy when duplicates are legitimate, or collect into a HashMap directly if nulls must survive.
You put logging in peek() to debug a stream, and nothing prints once the pipeline ends in count(). Is the stream broken?
No. Since JDK 9, count() may skip the pipeline entirely when the size is known from the source and no stage adds or removes elements, so peek never runs. Stream laziness means stages run only when the terminal operation needs them, which makes side effects in peek or map unreliable rather than merely bad style.
Why would you stream a large file rather than read it into memory, and what is backpressure?
Node.js stream backpressure prevents a fast producer from filling memory while a slow consumer catches up. The core signal is write() returning false and the producer waiting for drain before sending more.
Streams are lazy until a terminal operation runs. Why does that matter, and when would you make one parallel?
Laziness means intermediate operations only describe a pipeline, so nothing traverses the source until a terminal operation pulls, and short-circuiting operations can stop early. Parallel helps when the source splits evenly, the work per element is CPU-bound and substantial. Use this streams answer to show the decision, trade-off, and evidence rather than a memorised definition.
Walk me through writing your own Collector. What do its four functions do, and what do the characteristics promise the pipeline?
A collector is a supplier of a mutable container, an accumulator that folds one element into it, a combiner that merges two containers, and a finisher. The combiner runs only in parallel, which is why an untested combiner is the usual defect, and the characteristics tell the pipeline what it may skip or reorder.