Java Streams and Collectors Deep Quiz

A 4-question reference set on Java streams beyond the basics: laziness and short-circuiting, downstream collectors in groupingBy, toMap collision handling, and when parallel streams actually pay off.

Question Bundle
Java
4 questions
java-streams
java-lambdas
java-functional-interfaces
interview-prep

By CodeSnatch

December 6, 2025

·

Updated August 11, 2026

237 views

4

Rate

Java streams are lazy: intermediate operations defer until a terminal operation fires. What does this enable, and where does it bite when paired with side effects?

Examples

Example 1:

Input: list.stream().filter(x -> x > 100).map(this::loadOrder).findFirst()
Output: Stream short-circuits after the first match; loadOrder is called only once
Explanation: Laziness means filter+map fuse into one pass and stop at the terminal's first satisfied element.

Example 2:

Input: list.stream().peek(x -> log.info("seen {}", x)).filter(x -> x > 100).collect(toList())
Output: peek runs for every element, but ONLY because there's a downstream filter+collect; without a terminal op, peek runs zero times
Explanation: Side-effect-inside-stream is a smell; if the terminal op short-circuits or is removed, peek behavior changes.
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class Main {
    public record Order(int id) {}

    public Optional<Order> firstLargeOrder(List<Integer> ids) {
        return ids.stream()
                .filter(id -> id > 100)
                .map(this::loadOrder)
                .findFirst();
    }

    public List<Order> allLargeOrders(List<Integer> ids) {
        return ids.stream()
                .filter(id -> id > 100)
                .map(this::loadOrder)
                .collect(Collectors.toList());
    }

    private Order loadOrder(int id) {
        return new Order(id);
    }

    public static void main(String[] args) {
        Main m = new Main();
        List<Integer> ids = List.of(1, 50, 200, 300, 75, 400);
        System.out.println("first: " + m.firstLargeOrder(ids));
        System.out.println("all: " + m.allLargeOrders(ids));
    }
}