Autocoder

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.

IntroducedJava 8, with additions through 17
Core ideaLazy pipelines with one terminal operation
Typical useFilter, 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. 1

    What is a functional interface and which built-in ones should you know?

    easy

    A 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. 2

    How does a lambda differ from an anonymous inner class?

    medium

    In 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. 3

    What are the four kinds of method reference?

    medium

    Static 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.

    java
    Function<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 2
  4. 4

    What does this print? Show that streams are lazy and process element by element.

    medium

    Elements 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.

    java
    Stream.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 b
  5. 5

    What is the difference between map and flatMap?

    medium

    map 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.

    java
    List<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. 6

    Why does reusing a stream fail?

    medium

    A 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. 7

    Group employees by department and count them. What does Collectors.toMap do on duplicate keys?

    medium

    groupingBy(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.

    java
    record 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. 8

    Find the second highest salary with streams.

    medium

    Take 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).

    java
    OptionalInt second = es.stream().mapToInt(E::sal)
        .boxed().distinct().sorted(Comparator.reverseOrder())
        .skip(1).mapToInt(Integer::intValue).findFirst();
    System.out.println(second.orElse(-1));  // 50
  9. 9

    Count word frequencies in a sentence.

    easy

    Split, then group by identity with counting. Use LinkedHashMap if you want the first-seen order.

    java
    String 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. 10

    What are reduce, sum and average? Why can average return an OptionalDouble?

    medium

    reduce(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.

    java
    int 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.empty
  11. 11

    orElse versus orElseGet, and the main Optional rules.

    medium

    orElse(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. 12

    When are parallel streams a bad idea?

    hard

    They 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. 13

    Why must captured local variables be effectively final?

    medium

    A 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. 14

    Difference between Stream.toList() and collect(Collectors.toList())?

    medium

    Stream.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. 15

    What is the effect of limit on an infinite stream, and what does sorted do to laziness?

    hard

    Short-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.

    java
    System.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

See all in this section