← All topics
Start ▶
Streams and lambdas
Lambdas, functional interfaces, streams and Optional.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is the Stream API and how does it differ from a regular collection?
A stream is a "pipeline" that stores no data: it takes elements from a source (a list, an array, a file) and runs a chain of operations on them. A collection stores data, while a stream processes it.
2
What is a lambda expression and what is its syntax?
A lambda is a short anonymous function: parameters, an arrow -> and a body. It implements the single abstract method of a functional interface and is a much shorter form of an anonymous class.
3
What do you understand by a functional interface, and why is the @FunctionalInterface annotation needed?
A functional interface is an interface with one abstract method. A lambda can only be assigned to such an interface type. @FunctionalInterface is not mandatory, but if someone adds a second abstract method, the compiler reports an error.
4
How do the Function, Consumer, Supplier and Predicate interfaces differ from each other?
The difference is in input and output: Function<T,R> takes T and returns R; Consumer<T> takes a value and returns nothing; Supplier<T> takes nothing and gives T; Predicate<T> takes a value and returns boolean.
5
What kinds of method references are there? Give an example of each.
Four kinds: to a static method (Integer::parseInt), to a method of a specific object (System.out::println), to a method of an arbitrary object (String::toUpperCase) and to a constructor (ArrayList::new).
6
Explain the difference between intermediate and terminal operations.
An intermediate operation (filter, map, sorted) returns a new stream and doesn't run right away. A terminal operation (collect, forEach, count) produces a result and triggers the whole chain.
7
What do filter() and map() do? Give a simple example of using them together.
filter drops the elements that don't match a condition, so the count can shrink. map converts each element into another value: the count stays the same, and the type can change.
8
Can you use the same stream twice? What happens?
No. After a terminal operation the stream is closed, and touching it again throws IllegalStateException: stream has already been operated upon or closed. If you need it again, get a new stream from the source.
9
What's the difference between collect(Collectors.toList()) and stream.toList()?
Stream.toList() (Java 16+) returns an unmodifiable list. Collectors.toList() gives an ArrayList in practice, but its type and mutability are not guaranteed in the documentation.
10
Why was Optional invented?
Optional is there to show in a method's signature, openly, that "a value may or may not be present". It is mostly used as a return value, so the caller doesn't forget the empty case.
11
When do you use Optional.of(), Optional.ofNullable() and Optional.empty()?
of(x) when x is definitely not null; if null arrives it throws an NPE immediately. ofNullable(x) when x may be null, and it returns an empty Optional for null. empty() when you deliberately need an empty Optional.
12
Between stream().forEach() and a plain for-each loop, which do you pick and when?
For a simple iteration that returns no result, a for-each loop is often simpler: break, return and checked exceptions work. forEach is convenient for a side effect at the end of a filter/map chain.
13
In what ways can you create a stream?
stream() from a collection, Arrays.stream() from an array, Stream.of() from values, IntStream.range() for a range of numbers, Stream.iterate() and Stream.generate() for an infinite stream, and Files.lines() from a file.
14
How do you sort elements in a stream by several fields and in reverse order?
You give sorted() a Comparator: Comparator.comparing(...) for the main field, thenComparing(...) for the second field, and reversed() or Comparator.reverseOrder() for reverse order.
15
What do the distinct(), limit() and skip() operations do?
distinct() removes duplicate elements by equals, limit(n) keeps only the first n, and skip(n) discards the first n. All three are intermediate.
16
What do anyMatch, allMatch and noneMatch return on an empty stream?
On an empty stream anyMatch returns false, allMatch returns true and noneMatch returns true. Logically: "does any element match the condition?" no; "do all of them match?" there is no element that refutes it, so yes.
17
What is the difference between IntStream and Stream<Integer>?
IntStream works with the primitive int: there's no boxing and it has numeric methods like sum(), average() and max(). Stream<Integer> wraps each number in an Integer object and doesn't have such methods.
18
How do you join strings with Collectors.joining()?
joining() gathers the CharSequences in a stream into one string. You can also give a delimiter, a prefix and a suffix: joining(", ", "[", "]").
19
What is the difference between findFirst() and findAny()?
findFirst() returns the first element in encounter order. findAny() returns any one of them: in an ordinary stream it is usually the first, but in a parallel one it can be a different one each time. Both return an Optional.
20
Why can't you modify an outer local variable inside a lambda?
A lambda can only read an outer local variable, and it must be final or "effectively final". The reason: the lambda takes a copy of the variable, and it may run on another thread or later.
21
What does this code print to the console, and why?
Nothing is printed. peek and map are intermediate operations and there is no terminal operation, so the chain never runs at all.
22
Explain the difference between map() and flatMap() with an example.
map turns each element into one new value. flatMap produces a stream from each element and merges those streams into one flat stream, which is how you "unwrap" a nested structure.
23
How does reduce() work, and why is the identity value needed?
reduce folds the elements into one result: it starts from the identity and combines each element into the previous result with an accumulator. The identity is the starting value that is returned for an empty stream and doesn't distort the result.
24
How do you group elements with Collectors.groupingBy() and get the count in each group?
groupingBy(classifier) builds a Map<K, List<T>> by key. If you pass a downstream collector as the second argument, you get something other than a list: with counting() you get a count for each key.
25
What is the difference between partitioningBy and groupingBy, and when is each convenient?
partitioningBy splits into two groups by a predicate and returns a Map<Boolean, ...> whose keys are only true/false, and both keys are always present. groupingBy creates many groups by any key.
26
What happens when you use Collectors.toMap() and the same key comes twice?
You get IllegalStateException: Duplicate key. To prevent that, you pass a third argument, a merge function, which decides which of the two values to keep (or how to combine them).
27
Why is using Optional.get() dangerous, and what is the difference between orElse() and orElseGet()?
On an empty Optional, get() throws NoSuchElementException, which is just another name for an NPE. With orElse(x), x is always evaluated, while orElseGet(supplier) is called only when the Optional is empty.
28
In what order does a stream process elements: is every element filtered first and then every element mapped?
No. Each element goes through the chain one at a time, "vertically": the first element through filter, then map, then the terminal operation; then the second element. Only stateful operations like sorted collect all the elements.
29
What happens if you modify the source list inside a stream?
Usually you get a ConcurrentModificationException, or the result is unpredictable. Streams have a "non-interference" rule: the source must not be touched while the chain is running. Use removeIf to delete, and filter + toList for a new list.
30
How do you find the largest or smallest element in a stream, and what do you do when some fields are null?
Use max(comparator) or min(comparator): they return an Optional, because the stream may be empty. If the field being compared can be null, wrap it with Comparator.nullsFirst/nullsLast, otherwise you get an NPE.
31
How do you call a method that throws a checked exception inside a lambda?
The standard functional interfaces (Function, Consumer) don't declare checked exceptions, so you have to catch it inside the lambda and wrap it in an unchecked one. Options: try/catch with UncheckedIOException, a helper wrapper method, or your own functional interface.
32
After groupingBy, how do you get a sum, an average, or just a list of one field for each group?
The second argument of groupingBy is a downstream collector. Collectors like summingLong, averagingDouble, mapping, maxBy, toSet and collectingAndThen work inside each group, so you don't need separate processing afterward.
33
Where should you not use Optional?
Optional is meant mainly for a value returned from a method. Using it as an entity or DTO field, as a method parameter, or as a collection element, and returning Optional<List> instead of a collection, are widespread mistakes.
34
How do takeWhile() and dropWhile() differ from filter()?
filter checks every element. takeWhile takes elements until the condition fails for the first time and then stops; dropWhile discards that part and lets the rest through in full. Both were added in Java 9 and make sense on ordered data.
35
What is Collectors.teeing() and what problem does it solve?
teeing (Java 12+) feeds the stream to two collectors at once and combines their results with a function you provide. That way you can compute, say, both the count and the sum in a single pass.
36
What is wrong with the following code, and how do you fix it?
Writing to an outer list inside map is a side effect. On a sequential stream it looks like it works, but on a parallel one the ArrayList gets corrupted, and with a terminal operation like count() the map may not be called at all. The result should be gathered with a collector.
37
When and how do you write your own Collector?
When combinations of the ready-made collectors aren't enough, or when the same collecting logic is repeated in many places. The easiest way is Collector.of(supplier, accumulator, combiner, finisher): create a container, add an element, merge two containers and produce the final result.
38
How do you work with Optional without writing if (x.isPresent())? Use examples of map, flatMap, filter, or and ifPresentOrElse.
Optional has its own chaining methods: map transforms the value, flatMap works with a function that returns an Optional, filter adds a condition, or supplies a fallback Optional, and ifPresentOrElse handles both cases in one place.
39
What do you pay attention to when reading a large file with Files.lines()?
Files.lines reads the file lazily, line by line, so memory is saved even on a large file. But it holds an open file descriptor, so you must close the stream with try-with-resources. A read error surfaces as an UncheckedIOException.
40
What is mapMulti() and when is it more convenient than flatMap()?
mapMulti (Java 16+) lets you emit zero, one or several results from each element, but it doesn't create a new stream for each element: you accept the result into a Consumer. When an element yields few results, or the result type depends on a condition, it's lighter than flatMap.
41
What happens if you add results to an ArrayList with forEach in a parallel stream? How do you fix the code?
ArrayList is not thread-safe: if several ForkJoin threads call add at the same time, elements get lost, nulls appear, or an ArrayIndexOutOfBoundsException is thrown. The right way is collect/toList, which give each chunk its own container and merge them at the end.
42
What is a Spliterator and how do its characteristics affect how a stream works?
A Spliterator is the mechanism by which a stream pulls elements from a source and splits the source into parts. Its flags (SIZED, ORDERED, DISTINCT, SORTED, IMMUTABLE and others) let the stream optimize: skip unnecessary work, allocate an exactly sized array, and behave well in parallel.
43
Why can sorted() or distinct() make a program hang on an infinite stream?
sorted() can't emit even the first element until it has received all of them, and on an infinite stream there is no "all": it collects until memory runs out. distinct() does emit elements, but if no new unique value ever arrives, limit never fills and the stream doesn't stop.
44
How much does boxing affect stream performance, and how do you reduce it?
Every number in a Stream<Integer> is an Integer object on the heap (outside the -128..127 cache). At large volume that means many allocations, GC load and pointer chasing. Primitive variants like mapToInt/IntStream, comparingInt and summingLong remove that cost.
45
How does a lambda work inside the JVM, and how does it differ from an anonymous class?
An anonymous class compiles to a separate .class file and is created with new on each call. A lambda body becomes a private synthetic method in the same class, an invokedynamic sits at the call site, and LambdaMetafactory creates the implementation class at runtime on the first call.
46
Why does Collectors.toMap() throw an NPE on a null value, when HashMap accepts null?
toMap is built on HashMap.merge() semantics: the variant with a merge function calls merge directly, while the two-argument variant (Java 9+) checks the value with Objects.requireNonNull. By contract merge rejects a null value, so you get an NPE when the value, not the key, is null.
47
When do you need groupingByConcurrent() instead of groupingBy() on a parallel stream, and what does unordered() give you?
A parallel groupingBy builds a separate map for each chunk and then merges them, and with many keys the merge is expensive. groupingByConcurrent uses one ConcurrentHashMap that all threads write to and removes the merge, but order within a group isn't guaranteed.
48
Why can limit(), skip() and findFirst() be slow in parallel mode on an ordered stream?
On an ordered stream, "the first 10" means the first 10 in source order. In parallel each thread works on its own chunk, so to determine which elements really come first, the framework has to buffer results and wait for the earlier chunks. That is extra memory and synchronization.
49
How do you debug a bug in a long stream chain, and how do you read the stack trace?
The stack trace has many ReferencePipeline and Spliterator lines: skip them and find the lambda$... line in your own class. IntelliJ's Stream Trace (Java Stream Debugger) mode shows how elements changed at each stage, and pulling complex lambdas out into named methods makes debugging easier.
50
Why does a parallel reduce() sometimes give a wrong result? What requirements apply to the identity and the combiner?
A parallel reduce splits the source into chunks, starts each chunk from the identity and merges the results with the combiner. If the identity isn't truly neutral, the operation isn't associative, or the identity is a mutable object, the result changes with the number of threads.
51
Why does the signature of Stream.map() say Function<? super T, ? extends R>? If you write a utility that accepts a function, how do you place the wildcards?
This is the PECS rule: the function takes T (a consumer), so ? super T, and gives R (a producer), so ? extends R. That way you can pass a Function<Object, Integer> or a Predicate<Animal> to a Stream<Dog>. If you leave the wildcards out of your own utility, the caller runs into a confusing compile error.
52
When is choosing a strategy with a Map<Key, Function> instead of a big if/else or switch a good idea, and when is it bad?
If there are many strategies and they get added at runtime or from configuration, Map<Type, Function> (EnumMap for an enum) is convenient. But in Java 21 a sealed type and switch make the compiler check all cases, while in a map a forgotten key only shows up at runtime as a null.
53
Why doesn't this code compile, and how do you fix it?
The compiler infers a lambda parameter's type only from the target type. In a .reversed() chain the result of comparing(...) isn't assigned to anything, so u is taken as Object and u.name() isn't found. A method reference, an explicitly typed parameter or an explicit type argument solves the problem.
54
What happens if you make a recursive call inside map.computeIfAbsent for memoization?
Since Java 9, HashMap detects this and throws a ConcurrentModificationException. ConcurrentHashMap depending on the case throws IllegalStateException: Recursive update, or hangs on older JDKs. The mapping function must not modify that same map: write a recursive cache with plain get/put.
55
Why is calling Stream.concat() many times in a loop dangerous?
Each concat adds a new layer that wraps the previous two streams. If you chain thousands of them, pulling elements goes through deeply nested calls and fails with a StackOverflowError. To combine many sources, use Stream.of(...).flatMap(...).
56
This code gives different results on Java 8 and Java 17. Why?
Since Java 9, if count() knows the source size in advance (SIZED) and no operation in between changes the size, it doesn't run the pipeline at all. So the code inside peek is never called.
57
Do these two lines work the same? What's the difference in when a method reference and a lambda evaluate the receiver object?
No. config::timeout evaluates the receiver (config) at the moment the method reference is created: if it's null, the NPE appears immediately on that line, and even if the field is replaced later, the old object is still used. The lambda () -> config.timeout() reads config again on every call.
58
sorted() sometimes throws "Comparison method violates its general contract!". What causes it, and how do you write a comparator correctly?
The sorting algorithm (TimSort) throws an IllegalArgumentException if it notices that the comparator returned logically contradictory results. Common causes: overflow when comparing by subtraction, null or a mutable field, and a non-transitive "approximate" comparison. Use Integer.compare, comparingInt and nullsLast.
59
What happens if the function passed to Optional.map() returns null? And with flatMap?
If the result is null, map doesn't fail: it returns an empty Optional. That is why you can safely walk a chain of getters that return null. The function passed to flatMap, though, must return an Optional; if it returns null, you get an NPE.
60
Is sorted() in a stream stable? Is the original order of equal elements preserved?
On an ordered stream, yes: the Javadoc guarantees it, in parallel mode too. On an unordered stream (from a HashSet or after unordered()) there's no stability guarantee. Because of this property you can build a multi-level order with two sorts in a row or with thenComparing.
61
If several elements throw exceptions inside a parallel stream, what does the caller see, and what happens to the work on the other threads?
Only one exception reaches the calling thread; the others are usually lost. The other workers don't stop immediately: they may finish the elements they've already started, so side effects end up partially executed. In the stack trace you can also see that the error came from a different thread.
62
How do you count word frequencies and print the top 10 most frequent in descending order?
First build a Map<String, Long> with groupingBy(identity(), counting()), then sort entrySet().stream() by Map.Entry.comparingByValue().reversed() and limit(10). To preserve the result order you have to collect into a LinkedHashMap: a plain toMap gives a HashMap and the order is lost.
63
How do Stream.iterate() and Stream.generate() differ, and what do they return with limit() in parallel mode?
iterate computes each element from the previous one and gives an ordered stream. generate takes from an independent Supplier and gives an unordered stream. That's why a parallel generate().limit(n) returns any n elements, not "the first n", and the supplier may be called more than n times.
64
Does a stream inside flatMap short-circuit? What does findFirst() do with an infinite inner stream?
Since Java 10, yes: findFirst, limit and anyMatch stop the inner stream where needed too. In Java 8–9, flatMap read each inner stream to the end: with an infinite inner stream the program would hang, and with an expensive inner stream extra work would be done.
65
If a stream has null elements, which operations fail, and how do you clean out the nulls properly?
A stream itself allows null elements, but findFirst, max, min, sorted() with natural ordering, a toMap value, a groupingBy key and toUnmodifiableList throw an NPE on null. To clean up, use filter(Objects::nonNull), and for a single nullable value, Java 9's Stream.ofNullable.
66
What's the difference between Function.andThen and compose? How do you combine Predicates?
f.andThen(g) means f first, then g: g(f(x)). f.compose(g) means g first, then f: f(g(x)). Predicates combine with and, or, negate, and since Java 11 Predicate.not(...) is handy for negating a method reference.
67
What is the difference between stream.toArray() and toArray(String[]::new), and why does (String[]) stream.toArray() throw a ClassCastException?
toArray() with no arguments always returns an Object[]: even if it contains Strings, the array's type is Object[], and it can't be cast to String[]. For an array of the right type you pass a generator: toArray(String[]::new).
68
If a debug log needs expensive data to be computed, how do lambdas and Supplier help?
In log.debug("x={}", expensive()), expensive() is computed even when debug is off, because arguments are evaluated before the method is called. APIs that accept a Supplier (the SLF4J 2 fluent API, Log4j2, java.util.logging, Objects.requireNonNull) do the computation only when it's needed.
69
How do forEach and forEachOrdered differ, and what does forEachOrdered "cost" in a parallel stream?
forEach doesn't guarantee order: in parallel, elements arrive in any order and from several threads at once. forEachOrdered calls in source order, one at a time. The earlier stages (map, filter) still run in parallel, but the terminal action is sequential and results are buffered.
70
What does "salom".chars().forEach(System.out::println) print, and what do you watch for when streaming text by characters?
It prints numbers, not letters: chars() returns an IntStream and gives each UTF-16 code unit as an int (115, 97, ...). To get a character, use mapToObj(c -> (char) c). Emoji and other characters outside the BMP consist of two chars, and for them you need codePoints().
71
When does a parallel stream really speed things up, and when does it run slower than the sequential version? How do you decide?
Parallelism pays off only when the workload is large (number of elements × cost per element), the source splits well, the operations are independent and CPU-bound. With a small list, a LinkedList, I/O or a requirement to preserve order, it is often slower. The decision is made only by measurement.
72
An HTTP call was made inside a parallel stream and the whole service "froze". What happened, and how do you fix it?
All parallel streams share one ForkJoinPool.commonPool(), whose size is the core count minus one. Blocking I/O occupies the pool threads, and other parallel streams and the default executor of CompletableFuture stall as well. For I/O you need a separate executor or virtual threads.
73
You need to read and process millions of rows from the database using a Spring Data method that returns a Stream. How do you do it without filling memory and without errors?
A Stream<T> from a repository needs an open transaction and a DB cursor, and if the fetch size isn't set correctly the driver still loads everything into memory. On top of that, the persistence context holds every entity. You need fetch size, read-only, detach/clear, and try-with-resources, all of them.
74
In a JMH benchmark the stream pipeline came out as fast as a for loop, but in prod the same code is noticeably slower. What roles do "profile pollution" and a megamorphic call site play here?
Lambda calls inside a stream pass through a few shared places in JDK code (the ReferencePipeline sinks). In a benchmark only one lambda type is seen there, and the JIT inlines it. In prod hundreds of different lambdas pass through the same spot, the call site becomes megamorphic, and inlining and escape analysis stop. As a result virtual calls and boxing allocations come back.
75
Are streams slower than a plain for loop? If someone on the team says "streams are slow, we write for everywhere", what do you say?
In a small pipeline a stream has some extra overhead (lambdas, pipeline objects), but the JIT often narrows the gap, and in a real service it is invisible next to DB or network time. It isn't a general rule: on a specific hot path, decide by measuring with JMH.
76
MDC logs, SecurityContext or @Transactional stopped working inside a parallel stream. Why, and how do you fix it?
All of these are stored in a ThreadLocal. A parallel stream runs some of the elements on the calling thread and the rest on ForkJoinPool.commonPool workers, where the MDC is empty, there's no SecurityContext, and the connection bound to the transaction isn't visible. The result is the worst kind of bug: "sometimes works".
77
You need to find the top 10 largest elements in a stream of several million. Why is sorted().limit(10) bad, and how do you write it?
sorted() is stateful: it gathers all the elements into memory and sorts them fully, O(n log n) time and O(n) memory, even though the result you need is only 10. A min-heap (PriorityQueue) of size k needs just O(n log k) time and O(k) memory. For parallel, each chunk has its own heap and a combiner.
78
What are Stream Gatherers in Java 24 and what problem do they solve?
A gatherer is an intermediate operation you write yourself, the intermediate-stage equivalent of a Collector. It was a preview in Java 22–23 and became final in Java 24 (JEP 485). Things like sliding windows, grouping into batches and stateful filtering can be done without breaking the stream.
79
You've written a distinctByKey predicate to make objects unique by one field. What are its risks, especially on a parallel stream?
A stateful predicate inside filter (seen.add(key)) breaks the stream rules: in parallel it is undefined which duplicate survives, a reused predicate remembers old state, and the Set grows with the whole key set. The deterministic variant is toMap(key, identity(), (a, b) -> a, LinkedHashMap::new).
80
How can lambdas cause a memory leak? How do you find such a case in prod?
A lambda written inside an instance method can hold on to this (and through it the whole object graph). If such a lambda is put in a long-lived place (a static listener list, a cache, a scheduler), the object is never garbage collected. You find it in a heap dump by looking at the path to the GC root.
81
For a codebase that several teams work on, what rules would you write for using streams and lambdas, and how would you enforce them?
The rules should be few and clear: pipelines without side effects, no business logic in peek, parallel streams only by agreement, long lambdas moved into named methods. Enforcement comes through a linter, ArchUnit and a code review checklist, and style matters are settled by an automatic formatter.
82
When designing an internal library API, do you accept the standard functional interfaces (Function, Supplier) or create your own?
For simple, generic cases, the standard interfaces: the caller can pass any lambda or method reference. When a name carries meaning in the domain, when a checked exception is needed, or when you plan to add default methods in the future, your own @FunctionalInterface. The main cost is compatibility and overload problems.
83
Is it right to return a Stream<T> from a service or repository method, or should you always return a List?
Returning a Stream is lazy and convenient for large volumes, but it puts responsibility on the caller: it is single-use, may need closing, and is tied to an open resource (a transaction, a cursor). Within a module that's fine, but across a module or transaction boundary I usually return a List or a paged result.
84
How do you set an Optional policy across the domain model, REST DTO and JPA entity layers?
Optional only for methods that return a "might not be found" result: repository and service lookups. Entity and DTO fields stay plain nullable, and in the API contract optionality is expressed in the OpenAPI schema. The main goal is that where to expect null is the same across the whole codebase.
85
Should you ban parallel streams across the codebase? How do you justify the decision?
In web-service code I ban them by default: requests are already parallel, the common pool is a single one for the whole JVM, and if I/O gets in there everything stops. In batch or computation modules, exceptions backed by measurements are allowed. This is written as an ADR and checked with ArchUnit.
86
For data processing, how do you choose among Java Stream, Reactor (Flux) and virtual threads?
Stream is for processing data that is in memory or read synchronously, with one thread (or CPU-bound parallel). Reactor is for backpressure, asynchronous sources and long-lived streams. Virtual threads are for running lots of I/O in parallel with plain blocking code. The choice between the last two often depends on the team's experience.
87
You need to process several million records a day. When is a plain Java Stream pipeline enough, and when should you move to something like Spring Batch or Kafka Streams?
If the data fits in one JVM's memory and time window and restarting is simple, a stream is enough. If you need to resume from a restart, record partial failures, get monitoring and split across several instances, Spring Batch. If the data arrives continuously and you need stateful aggregation, Kafka Streams or something similar.
88
Should aggregation be done in Java with groupingBy or in SQL with GROUP BY? What rule do you set for the team?
The default: aggregate where the data is. For data in the database, SQL, because only the result comes over the network and indexes work. groupingBy in Java makes sense when the data is already in memory, comes from several sources, or the logic is too complex to express in SQL.
89
How do you handle errors in functional pipelines: stop at the first error or collect all errors and continue? How does this choice affect architecture?
This is a business question: in a payment batch a single error may need to cancel the whole batch (fail-fast), while in an import you need to save the good records and report the bad ones (collecting errors). For the second I model the outcome as a value, a Result type, and split it in two at the end of the pipeline.
90
Can you serialize a lambda? What are the risks of sending a function over the network in distributed systems?
You can, if the target type is Serializable or you use an intersection cast ((Runnable & Serializable) () -> ...). But a serialized lambda depends on the name of the synthetic method the compiler generated: if the code changes a little or versions differ, deserialization breaks. Captured values travel along too, and Java serialization brings security problems.
91
What contract do you set between modules for stream results and immutable collections? When is a defensive copy needed?
The agreement: public methods return unmodifiable collections (toList(), List.copyOf), and a collection that is received is copied before it is stored inside. That makes bugs about who modified whose list disappear. The cost is allocation, but it is usually unnoticeable.
92
The profiler shows a high allocation rate and frequent young GCs, and the flame graph has many stream and lambda frames. How do you analyze it, and when do you decide to rewrite the code?
First I find out whether the problem really is the stream or the boxing, intermediate collections and unnecessary objects inside it. JFR or async-profiler's allocation mode shows exactly which line allocates how much. I rewrite only with a measurable goal (p99, GC time) and only on a hot path.
93
In Java 21, what do you use instead of a parallel stream to call several services in parallel? What does structured concurrency change here?
For I/O fan-out, virtual threads: a separate virtual thread for each call, with plain blocking code. Structured concurrency (preview since Java 21, and still preview in Java 25) additionally binds the child tasks into one block: if one fails, the others are cancelled, and no thread is left "orphaned". A parallel stream is meant for CPU work.
94
You need to write a utility that exposes a paginated external API or table as a lazy Stream. How do you design it and what risks do you account for?
I write a Spliterator that loads each page when needed and wrap it with StreamSupport.stream: if the caller uses limit or takeWhile, extra pages aren't requested. Risks: no parallel splitting, partially consumed streams and open resources, data changing between pages, and retry and rate limits.
95
This calculation always gives the same result in tests, but in prod it is sometimes off by one tiyin. Explain the cause and the policy you need for financial calculations.
In a parallel stream a double sum is rounded differently depending on the order of the chunks, because floating-point addition isn't associative. The number of chunks depends on the core count, which differs between the test machine and the prod pod. For money you need BigDecimal or integer tiyin and a deterministic order.
96
Tests pass on a local machine but fail intermittently in CI; the cause turned out to be result order. How does encounter order work in streams, and how do you prevent such flaky tests?
A stream inherits the source's order: a List is ordered, a HashSet and HashMap aren't, and their iteration order depends on the hash, the capacity and the JDK version. If a test relies on order but the code doesn't guarantee it, it is flaky. The solution: if order is part of the contract, make it explicit in code; if not, the test should compare without regard to order.
97
You need to change a functional interface in a public library or an internal SDK in a new version. Which changes break users, and how do you evolve it?
Adding an abstract method, changing the signature or adding an overload breaks users' lambdas at compile time or at runtime. The safe way is to add only default and static methods; if a change is needed, a new interface, with the old one kept as @Deprecated and an adapter.
98
The team proposes adding a functional library like Vavr (Either, Try, immutable collections) to the project. How do you evaluate this decision?
The upside: errors and optionality are expressed in types, and composition is convenient. The cost: learning time for new developers, integration with Spring/JPA/Jackson, two kinds of collection worlds, and the library's long-term support. I usually propose starting with a small, bounded area and checking whether standard Java's sealed/record features are enough.
99
You're migrating a large codebase from Java 8 to Java 21. What risks and opportunities related to stream and lambda code do you put in the plan?
Risks: places where behavior changed (count() skipping peek, automatic replacement with toList(), Set.of ordering, changes in libraries), and pinning with virtual threads. Opportunities: simpler pipelines with toList, takeWhile, teeing, mapMulti, records and pattern matching. I first only raise the version, and do modernization separately, in small steps.
100
If you need to write logs, send metrics or call an external system inside a stream pipeline, how do you design that?
I try to keep the pipeline itself pure: the transformation separate, with side effects at the end, in the terminal operation or after the pipeline. For metrics, an aggregate result (how many processed, how many failed) is enough. External calls must be idempotent, bounded and ready to be retried, because a stream doesn't store a state like "where did it stop".
Sign up — studied questions get marked and your progress is saved.