Operations with streams: interview questions & scenarios
These are the stream-operations questions I use to check whether you can see the shape of a pipeline, not just remember method names. Answer it out loud first, then open the model answer, and revisit the lessons when a detail feels fuzzy: filter, map and flatMap, Slicing streams: skip, limit, takeWhile and dropWhile, Sorting, distinct and distinctBy, Stream.reduce and summing numbers, peek, forEach and side effects, Creating, merging and extending streams, Infinite streams with iterate and generate, Stream recipes: indices, last element and strings and Optional in stream pipelines.
Explain map versus flatMap using an order with line items.
Tests one-to-one shape, one-to-many shape, nested streams
Show answerHide answer
Model answer
map is a one-to-one transform. If you start with Stream<Order> and call .map(Order::id), each order becomes exactly one id, so the result is Stream<String>.
flatMap is zero-to-many or one-to-many. If each order has a list of line items, .map(Order::lines) gives a Stream<List<LineItem>>, while .flatMap(order -> order.lines().stream()) gives one flattened Stream<LineItem>.
List<String> skus = orders.stream()
.flatMap(order -> order.lines().stream())
.map(LineItem::sku)
.toList();
The interview trick is to describe the shape coming out. One output per input is map; a stream of outputs per input is flatMap.
How I’d say it in the interview
"I use map when each order turns into one value, like an id or total. I use flatMap when each order opens into another stream, like its line items, and I want one combined stream rather than a stream of lists."
Signals depth
Mentioning that flatMap(Optional::stream) is the Java 9+ way to turn present optionals into values and drop empty ones.
Red flags
"flatMap is just a faster map" or returning Stream<Stream<T>> when the caller asked for Stream<T>.
Follow-ups interviewers ask next
What if each order may have no line items?
That is exactly where
flatMapis useful. An empty line-item stream contributes zero elements to the result.What if I can emit zero or more items without creating small streams?
Since Java 16,
mapMultican be a lower-allocation alternative. I would still start withflatMapunless profiling or readability pushes me toward the callback style.
What does this print with a parallel stream, and what is wrong with the identity?
Tests reduce identity, parallel partitions, associativity
Show answerHide answer
Model answer
import java.util.List;
public class Main {
public static void main(String[] args) {
int total = List.of(1, 2, 3, 4).parallelStream()
.reduce(10, Integer::sum);
System.out.println(total);
}
}
On a normal Java 21 run this prints:
50
The bug is that 10 is not the identity for addition. In a parallel reduction, the identity can be used once per partition, not once for the whole pipeline. With four one-element partitions, you effectively get (10 + 1) + (10 + 2) + (10 + 3) + (10 + 4), which is 50.
For a real sum, use 0, or better for numbers:
int total = List.of(1, 2, 3, 4).stream()
.mapToInt(Integer::intValue)
.sum();
How I’d say it in the interview
"The identity has to be neutral. 10 changes every partial result, so parallel reduce can add it multiple times. For addition the identity is zero, and for a straight numeric sum I prefer a primitive stream."
Signals depth
Explaining why the same bad identity may look less surprising in a sequential stream, then fail the moment the pipeline is parallel.
Red flags
"Parallel streams are wrong here" without identifying the false identity value.
Follow-ups interviewers ask next
What if the operation were multiplication?
The identity should be
1, not0, because1 * x == x. The operation also needs to be associative for parallel reduction.What if I want to build a list with
reduce?Do not mutate a list inside
reduce. UsecollectortoList; mutable accumulation belongs in collectors.
What can this takeWhile over a Set print, and why is it a trap?
Tests takeWhile, encounter order, unordered sources
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
This code adds elements to an ArrayList inside parallelStream().forEach. What is the bug?
Tests side effects, non-interference, parallel forEach
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why can distinct().limit(3) hang on an infinite stream?
Tests infinite streams, stateful operations, limit ordering
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Write distinctByKey for a stream, and tell me when you would avoid it.
Tests distinctBy, stateful predicate, key equality
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Write a method that returns the first non-repeating character in a string.
Tests string streams, order preservation, grouping counts
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
How would you get the last element of a finite stream?
Tests reduce last, finite streams, list alternatives
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Implement in-memory pagination with streams. What is the cost trap?
Tests skip, limit, pagination cost, overflow
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
How do you "break" out of a forEach in a stream pipeline?
Tests forEach, short-circuiting, loop choice
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
How would you turn Stream<Optional<User>> into Stream<User>?
Tests Optional::stream, Java 8 fallback, flattening
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
This pipeline uses peek to save records. Why is that a bad design?
Tests peek, side effects, terminal behavior
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
How would you merge two streams and add one element at the beginning?
Tests Stream.concat, Stream.of, source order
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
You need sorted unique output. Should you call distinct().sorted() or sorted().distinct()?
Tests stateful operations, stability, equality versus comparator
Model answer, how to say it, 2 follow-ups: 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
Lessons in Operations with streams
- filter, map and flatMap
- Slicing streams: skip, limit, takeWhile and dropWhile
- Sorting, distinct and distinctBy
- Stream.reduce and summing numbers
- peek, forEach and side effects
- Creating, merging and extending streams
- Infinite streams with iterate and generate
- Stream recipes: indices, last element and strings
- Optional in stream pipelines