Streams API
35 questions in 10 subtopics.
Stream pipeline and laziness
What does it mean that streams are lazy? What does this print?Stream.of("a", "b", "c").filter(s -> {
System.out.println("filter " + s);
return true;
}).map(String::toUpperCase).findFirst();
list.stream().map(this::save); in a service method and no records are saved. Explain and fix it.How is a stream pipeline represented inside the JDK? Explain the role of stream flags such as SIZED, SORTED and DISTINCT and how they let operations be skipped.Streams were added in Java 8 as a library rather than language syntax such as LINQ in C#. What were the consequences of that choice, and how should a long-lived codebase use streams today?Intermediate and terminal operations
Classify these operations as intermediate or terminal, stateless or stateful, and short-circuiting or not: filter, map, sorted, distinct, limit, skip,forEach, collect, anyMatch, findFirst, reduce.What is the difference between Stream.toList() (Java 16) and collect(Collectors.toList())? Which would you use and when?This code sometimes throws IllegalStateException: stream has already been operated upon or closed. Supplier is not used.Stream<Order> s = repo.findAll().stream();
long c = s.count();
List<Order> l = s.toList();
Collectors and groupingBy
GivenList<Employee> with department() and salary(), write code that returns Map<String, Double> of average salary per department, and a Map<String, List<String>> of names per department sorted by name.Collectors.toMap(User::email, u -> u) throws IllegalStateException: Duplicate key. Another call throws NullPointerException. Explain both and fix them.Explain partitioningBy, teeing (Java 12), collectingAndThen, and downstream collectors such as counting, summingInt, maxBy and flatMapping (Java 9). Give one use case for teeing.Write a custom Collector that collects strings into a single comma-separated string with a maximum of 100 characters, and explain the role of supplier, accumulator, combiner, finisher and characteristics.Your analytics team aggregates millions of records in memory with groupingBy on several keys. Memory and GC time are high. How do you review the design?Over years, more aggregation logic moved from SQL into Java stream code, and some services now load large data sets to group them in memory. How would you decide where aggregation belongs in your architecture, and what would you standardise?FlatMap
GivenList<Order> where each Order has List<Line> lines(), produce a list of distinct product ids across all orders. Then explain how flatMap differs from map.Before JDK 10, flatMap was not lazy: Stream.of(1).flatMap(i -> Stream.iterate(0, x -> x + 1)).findFirst() never finished. Explain why and when mapMulti may be preferable to flatMap.Reduce
Explain the three forms ofStream.reduce. Why must the identity value be a true identity and the accumulator associative?This code returns different totals on each run when the stream is parallel:BigDecimal total = list.parallelStream().reduce(BigDecimal.ZERO, (a, b) -> a.add(b).setScale(2, RoundingMode.HALF_UP), BigDecimal::add);
Parallel streams
How does a parallel stream run? Which thread pool does it use and why can using it in a web server be a problem?When is a parallel stream likely to be faster than sequential? Explain the role of data size, source splitting and per-element cost.A developer changesstream() to parallelStream() on a list of 200 items, each requiring an HTTP call, to speed up an endpoint. Under load latency gets worse. Why, and what would you do instead?Should your organisation allow parallel streams in server-side code? Write the guideline you would publish and explain the reasoning.Parallel streams were promoted in Java 8 as easy parallelism, yet many organisations now restrict them. Why did practice diverge from the promise, and what does that teach about adopting easy-looking performance features?Spliterators
What is a Spliterator and what dotryAdvance, trySplit, estimateSize and characteristics do? Why does a good trySplit matter?Write a Stream that reads records from a paged REST API lazily, fetching the next page only when needed. Which approach would you use: Spliterator, Iterator or Stream.iterate?Stream gatherers
What are stream gatherers, final in Java 24? Name some built-in gatherers and what they do.Using a gatherer, write a pipeline that turns a stream of temperature readings into a stream of 5-reading moving averages. Then explain the parts of the Gatherer interface.Before gatherers, teams wrote custom Collectors, Spliterators or loops for things like batching or deduplicating consecutive elements. How would you decide when to use a custom gatherer in shared code?A team proposes usingGatherers.mapConcurrent to call a downstream service for each element of a large stream. What do you check before approving it for production?Gatherers became final in Java 24. Your fleet is split between Java 21 and 25. How do you guide teams and shared library owners on adopting gatherers?Stream pitfalls and debugging
A stream pipeline gives the wrong result and a colleague addspeek(System.out::println) to debug it, but nothing is printed for some stages. Explain why and better ways to debug streams.This code sometimes throws ConcurrentModificationException or loses elements:List<String> out = new ArrayList<>();
items.parallelStream().filter(this::valid).forEach(out::add);
groupingBy inside a flatMap. It works, but nobody can follow it. How do you give feedback and what do you suggest?Streams have been in Java for over a decade. What patterns of misuse have you seen cause incidents or maintenance cost, and which of them would you forbid or require review for in an organisation-wide standard?Primitive streams
Why doIntStream, LongStream and DoubleStream exist? Show how to convert between object and primitive streams and name operations only primitive streams have.A service computing totals with list.stream().map(Order::amount).reduce(0, Integer::sum) shows high allocation in a profiler and sometimes an incorrect total for large values. What is wrong?No question matches these choices.