Stream basics: interview questions & scenarios
These are the stream-basics questions I use to check whether you can see the source, pipeline stages and terminal operation behind fluent Java code. Answer it out loud first, then open the model answer, and revisit the lessons when a detail feels fuzzy: Introduction to Java streams, How a stream pipeline executes, Intermediate vs terminal operations, findFirst vs findAny and short-circuiting and Primitive streams: IntStream, LongStream and DoubleStream.
What is a Java stream, and how is it different from a collection?
Tests stream shape, source versus pipeline, terminal operation
Show answerHide answer
Model answer
A Java stream is a one-shot pipeline over a source. The source can be a List, array, file, generated sequence or custom Spliterator; the stream describes operations to apply as elements are pulled through. A collection stores elements. A stream does not store elements as its main job, and it is not meant to be reused after a terminal operation.
The shape is:
source -> intermediate operations -> terminal operation
filter, map, peek, sorted and limit are intermediate operations because they return another stream. count, sum, toList, findFirst, forEach and collect are terminal operations because they start traversal and produce a result or final side effect.
How I’d say it in the interview
"A stream is a recipe over a source, not the pantry. The list owns the data; the stream records the pipeline. Nothing really moves until a terminal operation pulls, and after that pull the stream is consumed."
Signals depth
Saying that some operations, like sorted and distinct, may buffer during execution, but that does not turn the stream into a reusable collection.
Red flags
"A stream is a faster list" or "a stream stores filtered results after each step".
Follow-ups interviewers ask next
What if I need to traverse the same data twice?
Store the source, such as the
List,Pathor query description, and create a fresh stream for each traversal. If the result is small and expensive to recompute, materialize it deliberately into a collection and say that cost out loud.What if the source is a file?
A stream from
Files.lines(path)is resource-backed, so use try-with-resources. Collection streams usually do not need manual closing.
What does this print, and why does peek wait until count()?
Tests laziness, vertical traversal, terminal operation
Show answerHide answer
Model answer
import java.util.List;
public class Main {
public static void main(String[] args) {
var pipeline = List.of("ann", "bob", "carla").stream()
.peek(name -> System.out.println("peek " + name))
.filter(name -> name.length() > 3)
.map(name -> {
System.out.println("map " + name);
return name.toUpperCase();
});
System.out.println("built");
System.out.println(pipeline.toList());
}
}
It prints:
built
peek ann
peek bob
peek carla
map carla
[CARLA]
The intermediate operations are lazy. Creating pipeline builds stage objects; it does not traverse the list. toList() is the terminal operation, so it starts pulling elements through the chain. For a stateless sequential pipeline, elements move vertically: ann is peeked and filtered out, bob is peeked and filtered out, then carla is peeked, mapped and added to the result.
How I’d say it in the interview
"The only line before traversal is built. Then the terminal operation pulls one name at a time. The first two names never reach map, and carla goes from peek to filter to map before the final list is printed."
Signals depth
Mentioning vertical execution and operation fusion, not imagining a temporary list after every intermediate operation.
Red flags
Printing all peek lines when the pipeline is created, or printing map carla before the peeks for ann and bob.
Follow-ups interviewers ask next
What if the terminal operation were removed?
Only
builtwould print. A pipeline with no terminal operation is a description, not a traversal.What if this were a parallel stream?
Laziness still applies, but print order becomes a poor teaching tool because multiple elements can be processed by different worker threads.
What does this print on Java 21, and why can count() skip peek?
Tests SIZED flag, count optimization, peek side effects
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why does this code throw IllegalStateException: stream has already been operated upon or closed, and how would you fix it?
Tests one-shot streams, linked pipeline, supplier pattern
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Which operations here are intermediate and which are terminal, and what runs when?
Tests operation categories, laziness, return types
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
When would you use a stream, and when would you keep a loop?
Tests readability, side effects, control flow trade-off
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
What is the difference between findFirst() and findAny()?
Tests encounter order, short-circuiting, parallel choice
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
What does this print, and why does the infinite stream terminate?
Tests short-circuiting, infinite streams, findFirst
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why would you write mapToInt(Order::cents).sum() instead of map(Order::cents).reduce(0, Integer::sum)?
Tests primitive streams, boxing, numeric terminals
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Write a method that returns the first paid order id, or Optional.empty() if none exists.
Tests filter, map, findFirst, Optional
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
This pipeline uses sorted().findFirst() to get the cheapest product. What would you change?
Tests stateful operations, min, unnecessary sorting
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Write a method that counts non-blank lines in a file. What stream detail must the method handle?
Tests resource-backed streams, try-with-resources, predicates
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Premium question set
Keep reading with the Java Pass
The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.
From ₹199 · one-time payment · No auto-renewal