Java 8 Streams and Lambdas Interview Questions
Last updated 2026-11-19
Streams and lambdas are the Java 8 features every interviewer checks, because they change how collection code is written. Expect three kinds of question: conceptual (what is a functional interface), output prediction (the order in which a lazy pipeline runs) and short coding tasks (second highest salary, word frequency, grouping).
The snippets use features that exist in Java 17, including Stream.toList() from Java 16. Related collection behaviour is on the collections page.
| Introduced | Java 8, with additions through 17 |
|---|---|
| Core idea | Lazy pipelines with one terminal operation |
| Typical use | Filter, map, group and aggregate collections |
Pipeline anatomy
A stream pipeline has a source (a collection, array or generator), zero or more intermediate operations that return another stream (filter, map, sorted) and exactly one terminal operation (collect, forEach, count) that triggers execution. Nothing runs until the terminal operation is called, and each element flows through the whole pipeline before the next one starts, except at stateful operations such as sorted.
Java 8 Streams and Lambdas Interview Questions: questions with worked answers
1 What is a functional interface and which built-in ones should you know?
easyA functional interface has exactly one abstract method, so a lambda or method reference can implement it; @FunctionalInterface makes the compiler enforce that. Know Predicate<T> (test), Function<T,R> (apply), Consumer<T> (accept), Supplier<T> (get), BiFunction, UnaryOperator<T> and BinaryOperator<T>. Primitive variants such as IntPredicate and ToIntFunction avoid boxing. Default and static methods do not count towards the single-method rule.
2 How does a lambda differ from an anonymous inner class?
mediumIn a lambda, this refers to the enclosing instance, while in an anonymous class this is the anonymous object itself. Lambdas compile to invokedynamic and do not generate a separate class file per lambda, and they can implement only functional interfaces. Anonymous classes can hold state, implement multi-method interfaces and shadow variables, which lambdas cannot.
3 What are the four kinds of method reference?
mediumStatic method (Integer::parseInt), bound instance (System.out::println, where the receiver is a specific object), unbound instance (String::length, where the first parameter is the receiver) and constructor (ArrayList::new). The compiler matches the reference to the functional interface signature.
javaFunction<String,Integer> f = String::length; // unbound Supplier<List<String>> s = ArrayList::new; // constructor Consumer<String> p = System.out::println; // bound List.of("a","bb").stream().map(f).forEach(System.out::println); // 1 24 What does this print? Show that streams are lazy and process element by element.
mediumElements flow through the pipeline one at a time and findFirst short-circuits, so after "b" passes the filter and map, nothing else is evaluated. Without the terminal operation the pipeline would print nothing.
javaStream.of("a", "b", "c") .filter(s -> { System.out.println("filter " + s); return !s.equals("a"); }) .map(s -> { System.out.println("map " + s); return s.toUpperCase(); }) .findFirst(); // filter a // filter b // map b5 What is the difference between map and flatMap?
mediummap transforms each element to exactly one output, so a Stream<List<T>> stays nested. flatMap maps each element to a stream and flattens those streams into one. Use it to flatten lists of lists, split lines into words or unwrap Optionals.
javaList<List<Integer>> nested = List.of(List.of(1, 2), List.of(3)); System.out.println(nested.stream().flatMap(List::stream).toList()); // [1, 2, 3] System.out.println(Stream.of("a b", "c").flatMap(s -> Arrays.stream(s.split(" "))).toList()); // [a, b, c]6 Why does reusing a stream fail?
mediumA stream can be consumed only once. After a terminal operation it is closed, and any further operation throws IllegalStateException: stream has already been operated upon or closed. Create a new stream from the source, or hold a Supplier<Stream<T>>.
7 Group employees by department and count them. What does Collectors.toMap do on duplicate keys?
mediumgroupingBy(classifier, downstream) builds a Map of lists or any downstream result. toMap throws IllegalStateException when two elements map to the same key unless you supply a merge function as the third argument. partitioningBy always yields keys true and false.
javarecord E(String name, String dept, int sal) {} List<E> es = List.of(new E("A","IT",50), new E("B","IT",70), new E("C","HR",40)); Map<String,Long> cnt = es.stream().collect(Collectors.groupingBy(E::dept, Collectors.counting())); System.out.println(cnt); // {HR=1, IT=2} Map<String,Integer> max = es.stream().collect( Collectors.toMap(E::dept, E::sal, Math::max)); // merge function avoids the exception System.out.println(max); // {HR=40, IT=70}8 Find the second highest salary with streams.
mediumTake distinct salaries, sort descending, skip one and take the first, returning an Optional because the list may have fewer than two values. This is O(n log n); a single pass with two variables is O(n).
javaOptionalInt second = es.stream().mapToInt(E::sal) .boxed().distinct().sorted(Comparator.reverseOrder()) .skip(1).mapToInt(Integer::intValue).findFirst(); System.out.println(second.orElse(-1)); // 509 Count word frequencies in a sentence.
easySplit, then group by identity with counting. Use LinkedHashMap if you want the first-seen order.
javaString text = "to be or not to be"; Map<String, Long> freq = Arrays.stream(text.split(" ")) .collect(Collectors.groupingBy(w -> w, LinkedHashMap::new, Collectors.counting())); System.out.println(freq); // {to=2, be=2, or=1, not=1}10 What are reduce, sum and average? Why can average return an OptionalDouble?
mediumreduce(identity, op) folds elements with an associative operator; sum on IntStream is its specialised form. average has no meaningful result for an empty stream, so it returns OptionalDouble. Prefer mapToInt then sum over reduce(0, Integer::sum) on boxed values to avoid boxing.
javaint total = List.of(1, 2, 3, 4).stream().reduce(0, Integer::sum); // 10 System.out.println(IntStream.rangeClosed(1, 5).sum()); // 15 System.out.println(IntStream.empty().average()); // OptionalDouble.empty11 orElse versus orElseGet, and the main Optional rules.
mediumorElse(x) evaluates x eagerly even when a value is present, while orElseGet(supplier) runs the supplier only if the Optional is empty. Use orElseGet for anything costly. Optional is intended as a return type, not for fields, parameters or collections, and Optional.get() without isPresent is discouraged in favour of orElseThrow. Optional.of(null) throws, while ofNullable(null) returns empty.
12 When are parallel streams a bad idea?
hardThey split the source over the common ForkJoinPool, so they help only when the work per element is CPU heavy, the data is large, the source splits well (arrays, ArrayList) and the operations are stateless and associative. They hurt for small data, LinkedList sources, blocking I/O (which starves the shared pool), and any lambda that mutates shared state. forEach order is not preserved; use forEachOrdered if needed.
13 Why must captured local variables be effectively final?
mediumA lambda copies the value of local variables it uses, and the original variable may be gone when it runs, possibly on another thread. Allowing mutation would make the copy inconsistent, so the compiler requires variables to be final or never reassigned. Fields are exempt because they are read through this. Use an array element or AtomicInteger if you truly need a mutable counter.
14 Difference between Stream.toList() and collect(Collectors.toList())?
mediumStream.toList() (Java 16) returns an unmodifiable list and allows null elements. Collectors.toList() returns a mutable ArrayList in practice, but the specification gives no guarantee about the type or mutability. Use collect(Collectors.toCollection(ArrayList::new)) when you need to modify the result.
15 What is the effect of limit on an infinite stream, and what does sorted do to laziness?
hardShort-circuit operations such as limit, findFirst and anyMatch let an infinite stream terminate. sorted is stateful and must see every upstream element before emitting the first one, so it breaks element-by-element flow and cannot be used on an infinite stream without a limit before it.
javaSystem.out.println(Stream.iterate(1, x -> x * 2).limit(5).toList()); // [1, 2, 4, 8, 16] System.out.println(Stream.iterate(1, x -> x < 50, x -> x * 3).toList()); // [1, 3, 9, 27]
Frequently asked questions
Are streams faster than for loops?
Not necessarily. They are about clarity and composability; a simple loop is often equal or faster for small data. Parallel streams can help only on large CPU-bound work.
Can I modify the source while streaming?
No. Interfering with the source during a pipeline can throw ConcurrentModificationException or give unpredictable results.
What is peek for?
Debugging only. It is intermediate and may be skipped, for example when count() can compute the size directly.
Which Java 8 features are asked besides streams?
Default methods, Optional, the java.time API, CompletableFuture and method references. See Java interview questions.
Related guides
More in Programming Language Interview Questions by Language
- Java Coding Interview Questions
- Java Collections Interview Questions
- Java Concurrency Utilities Interview Questions
- Java Exception Handling Interview Questions
- Java Garbage Collection Interview Questions
- Java Generics Interview Questions
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers
- Java Multithreading Interview Questions
- Java OOPs Interview Questions
- Java String Interview Questions