Scrivio Interview library

Streams API

35 questions in 10 subtopics.

Stream pipeline and laziness

ConceptFoundations5 min read
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();
DebuggingFoundations5 min read
A developer writes list.stream().map(this::save); in a service method and no records are saved. Explain and fix it.
InternalsIntermediate7 min read
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.
LeadershipPrincipal6 min read
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

ConceptFoundations5 min read
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.
CodingFoundations5 min read
What is the difference between Stream.toList() (Java 16) and collect(Collectors.toList())? Which would you use and when?
DebuggingIntermediate6 min read
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();
Explain and fix.

Collectors and groupingBy

CodingFoundations5 min read
Given List<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.
DebuggingFoundations6 min read
Collectors.toMap(User::email, u -> u) throws IllegalStateException: Duplicate key. Another call throws NullPointerException. Explain both and fix them.
ConceptIntermediate6 min read
Explain partitioningBy, teeing (Java 12), collectingAndThen, and downstream collectors such as counting, summingInt, maxBy and flatMapping (Java 9). Give one use case for teeing.
CodingIntermediate6 min read
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.
DesignAdvanced6 min read
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?
LeadershipPrincipal6 min read
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

CodingFoundations6 min read
Given List<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.
InternalsIntermediate7 min read
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

ConceptFoundations7 min read
Explain the three forms of Stream.reduce. Why must the identity value be a true identity and the accumulator associative?
DebuggingIntermediate7 min read
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);
What is wrong?

Parallel streams

ConceptFoundations7 min read
How does a parallel stream run? Which thread pool does it use and why can using it in a web server be a problem?
ConceptIntermediate7 min read
When is a parallel stream likely to be faster than sequential? Explain the role of data size, source splitting and per-element cost.
ScenarioIntermediate7 min read
A developer changes stream() 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?
LeadershipAdvanced7 min read
Should your organisation allow parallel streams in server-side code? Write the guideline you would publish and explain the reasoning.
LeadershipPrincipal6 min read
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

InternalsIntermediate7 min read
What is a Spliterator and what do tryAdvance, trySplit, estimateSize and characteristics do? Why does a good trySplit matter?
CodingIntermediate7 min read
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

ConceptFoundations6 min read
What are stream gatherers, final in Java 24? Name some built-in gatherers and what they do.
CodingIntermediate7 min read
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.
DesignIntermediate7 min read
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?
ScenarioAdvanced7 min read
A team proposes using Gatherers.mapConcurrent to call a downstream service for each element of a large stream. What do you check before approving it for production?
LeadershipAdvanced6 min read
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

DebuggingFoundations6 min read
A stream pipeline gives the wrong result and a colleague adds peek(System.out::println) to debug it, but nothing is printed for some stages. Explain why and better ways to debug streams.
DebuggingIntermediate6 min read
This code sometimes throws ConcurrentModificationException or loses elements:
List<String> out = new ArrayList<>();
items.parallelStream().filter(this::valid).forEach(out::add);
Explain and fix.
ScenarioIntermediate7 min read
A code review shows a stream pipeline with eight chained operations, nested lambdas and a groupingBy inside a flatMap. It works, but nobody can follow it. How do you give feedback and what do you suggest?
LeadershipPrincipal7 min read
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

ConceptFoundations6 min read
Why do IntStream, LongStream and DoubleStream exist? Show how to convert between object and primitive streams and name operations only primitive streams have.
DebuggingIntermediate7 min read
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?