Interview Questions
Streams API · Study material
Java Streams API – Interview Questions
1. What is a stream?
A sequence of elements supporting functional-style aggregate operations; it does not store data or modify its source.
2. Collection vs Stream?
A collection stores elements; a stream computes over them lazily, once, and can be infinite.
3. Intermediate vs terminal operations?
Intermediate operations return a stream and are lazy; terminal operations produce a result and trigger execution.
4. map vs flatMap?
map produces one output per input; flatMap maps each input to a stream and flattens them.
5. What is lazy evaluation in streams?
Intermediate operations do nothing until a terminal operation runs; then elements are processed one by one through the pipeline.
6. What are short-circuiting operations?
Operations that can finish without examining every element: limit, findFirst, findAny, anyMatch, allMatch, noneMatch, takeWhile.
7. Can a stream be reused?
No; a second terminal operation throws IllegalStateException.
8. What does reduce do?
Combines elements into one value using an identity and an associative accumulator (e.g. sum, max, concatenation).
9. findFirst vs findAny?
findFirst respects encounter order; findAny may return any element and is faster in parallel streams.
10. What is the difference between peek and forEach?
peek is an intermediate operation for debugging; forEach is terminal.
11. What do groupingBy and partitioningBy do?
groupingBy builds a Map by a classifier; partitioningBy builds a Map<Boolean, …> by a predicate.
12. How do you convert a stream to a map?
collect(Collectors.toMap(keyFn, valueFn[, mergeFn[, mapFactory]])).
13. What happens with duplicate keys in toMap?
IllegalStateException unless a merge function is supplied.
14. Why use IntStream?
To avoid boxing and to get numeric operations like sum, average and range.
15. What is Stream.iterate vs Stream.generate?
iterate builds each element from the previous one; generate calls a Supplier each time. Both can be infinite.
16. Stream.toList vs Collectors.toList?
Stream.toList returns an unmodifiable list; Collectors.toList guarantees nothing about mutability.
17. What are parallel streams?
Streams whose work is split across threads using the common ForkJoinPool.
18. When are parallel streams a bad idea?
Small data, I/O-bound work, ordering requirements, or shared mutable state.
19. Does a stream modify its source?
No; it produces new results (though the source must not be modified during the pipeline).
20. What is Collectors.teeing?
A Java 12 collector that feeds elements to two collectors and merges their results.