Streams, lambdas and Optional

Junior Always asked 8 min

On this page

The question

What is the difference between intermediate and terminal stream operations?

30-second answer

Intermediate operations such as filter, map and sorted return a new Stream and only describe work; they are lazy. A terminal operation such as collect, count, forEach or findFirst runs the pipeline and produces a result or a side effect. Each pipeline has exactly one terminal operation, after which the stream is consumed and cannot be reused.

Understand it

A lazy stream, one element at a time

Step by step

filter and map only describe the pipeline. Without a terminal operation nothing runs, so no element has been read.

Step 1 of 5
View as text

Four source elements sit in a row at the top: "al", "bob", "cy" and "dan". Below them are three stages, one under another: filter with length greater than 2, map with toUpperCase, and findFirst(). A badge counts the elements read.

filter and map only describe the pipeline. Without a terminal operation nothing runs, so no element has been read. The badge reads 0 of 4.

Calling findFirst(), the terminal operation, starts the work. It pulls elements from the source one at a time, beginning with "al". An arrow runs from the findFirst() stage up to "al".

"al" has length 2, so it fails the filter and is dropped. It never reaches map. The "al" token stops in the filter stage, marked dropped.

"bob" passes the filter and map turns it into "BOB". Each element runs the whole pipeline before the next one is read. The filter stage marks "bob" as passing, and the map stage shows "bob" becoming "BOB".

findFirst() has its match and stops, returning Optional[BOB]. "cy" and "dan" are never read: 2 of 4 elements did all the work. "BOB" reaches the findFirst() stage, and "cy" and "dan" are dashed and marked never read.

Four source elements sit in a row at the top: "al", "bob", "cy" and "dan". Below them are three stages, one under another: filter with length greater than 2, map with toUpperCase, and findFirst(). A badge counts the elements read.

filter and map only describe the pipeline. Without a terminal operation nothing runs, so no element has been read. The badge reads 0 of 4.

Calling findFirst(), the terminal operation, starts the work. It pulls elements from the source one at a time, beginning with "al". An arrow runs from the findFirst() stage up to "al".

"al" has length 2, so it fails the filter and is dropped. It never reaches map. The "al" token stops in the filter stage, marked dropped.

"bob" passes the filter and map turns it into "BOB". Each element runs the whole pipeline before the next one is read. The filter stage marks "bob" as passing, and the map stage shows "bob" becoming "BOB".

findFirst() has its match and stops, returning Optional[BOB]. "cy" and "dan" are never read: 2 of 4 elements did all the work. "BOB" reaches the findFirst() stage, and "cy" and "dan" are dashed and marked never read.

Takeaway: Intermediate operations only build the pipeline. The terminal operation pulls elements one at a time, and findFirst() stops as soon as it has a match.

map or flatMap on lists of items?

Compare

map(Order::items) turns each order into one List: [[a, b], [c, d, e], []] becomes a stream of 3 lists, the empty one included.

View as text

Three orders sit in a row at the top as boxes of items: a and b in the first, c, d and e in the second, and the third is empty. An arrow leads down to the resulting stream, labelled with the operation.

map: map(Order::items) turns each order into one List: [[a, b], [c, d, e], []] becomes a stream of 3 lists, the empty one included. The stream holds the same three boxes, including the empty one. A badge reads 3 elements, each a List, and a note says the empty list is still 1 element.

flatMap: flatMap(o -> o.items().stream()) replaces each order with the stream of its items: [[a, b], [c, d, e], []] becomes a stream of 5 strings. The boxes disappear and the letters a, b, c, d and e slide into one flat row. A badge reads 5 elements, each a String, and a note says the empty list adds 0 elements.

Three orders sit in a row at the top as boxes of items: a and b in the first, c, d and e in the second, and the third is empty. An arrow leads down to the resulting stream, labelled with the operation.

map: map(Order::items) turns each order into one List: [[a, b], [c, d, e], []] becomes a stream of 3 lists, the empty one included. The stream holds the same three boxes, including the empty one. A badge reads 3 elements, each a List, and a note says the empty list is still 1 element.

flatMap: flatMap(o -> o.items().stream()) replaces each order with the stream of its items: [[a, b], [c, d, e], []] becomes a stream of 5 strings. The boxes disappear and the letters a, b, c, d and e slide into one flat row. A badge reads 5 elements, each a String, and a note says the empty list adds 0 elements.

Takeaway: map gives exactly one output per input, so lists stay lists. flatMap replaces each input with a stream of its items and joins them into one stream.

A stream pipelineA pipeline starts from a source such as a list. Intermediate operations like filter and map are lazy and only describe the work. One terminal operation such as findFirst or collect runs the pipeline, pulling elements from the source one at a time, and produces the result.Source: list.stream()filter: lazymap: lazyOne terminaloperation: findFirstRuns it: a value orOptional
A stream pipelineA pipeline starts from a source such as a list. Intermediate operations like filter and map are lazy and only describe the work. One terminal operation such as findFirst or collect runs the pipeline, pulling elements from the source one at a time, and produces the result.Source: list.stream()filter: lazymap: lazyOne terminaloperation: findFirstRuns it: a value orOptional
A stream pipeline: source, lazy steps, one terminal operation

In code

Optional<String> first = Stream.of("al", "bob", "cy", "dan")
    .peek(n -> System.out.println("visit " + n))
    .filter(n -> n.length() > 2)
    .map(String::toUpperCase)
    .findFirst();          // prints: visit al, visit bob
System.out.println(first); // Optional[BOB]
findFirst reads only what it needs
record Order(List<String> items) {}

List<Order> orders = List.of(
    new Order(List.of("a", "b")),
    new Order(List.of("c", "d", "e")),
    new Order(List.of()));
List<List<String>> nested = orders.stream()
    .map(Order::items).toList();                // [[a, b], [c, d, e], []]: 3 lists
List<String> flat = orders.stream()
    .flatMap(o -> o.items().stream()).toList(); // [a, b, c, d, e]: 5 strings
map keeps the lists, flatMap joins their items
The findFirst tracefindFirst pulls the first element, al, which has length 2 and is dropped by the filter. It pulls bob, which passes the filter and is mapped to BOB. findFirst returns Optional of BOB and stops, so cy and dan are never read.findFirst() pullsal: length 2, droppedbob: passes the filtermap: bob becomesBOBReturnsOptional[BOB]cy and dan: neverread
The findFirst tracefindFirst pulls the first element, al, which has length 2 and is dropped by the filter. It pulls bob, which passes the filter and is mapped to BOB. findFirst returns Optional of BOB and stops, so cy and dan are never read.findFirst() pullsal: length 2, droppedbob: passes the filtermap: bob becomesBOBReturnsOptional[BOB]cy and dan: neverread
The findFirst trace: al is dropped, bob is the answer
 Wrong User a = findUser(id).orElse(loadDefaultUser());         // loadDefaultUser() runs even when the user exists
 Right User b = findUser(id).orElseGet(this::loadDefaultUser);  // runs only when the Optional is empty
orElse always runs its argument; orElseGet only when empty

Solve it

Return the names of the top 3 customers by total spend

You get a List<Order>, each with a customer name and an amount in cents. Return the three customers who spent the most, highest first. Write it with streams and explain its cost.

  1. Clarify. Totals per customer, not single orders. Fewer than three customers returns fewer names; ties keep any order.
  2. Group and sum. groupingBy(Order::customer, summingLong(Order::cents)) builds one total per customer in a single pass.
  3. Sort and cut. Stream the map’s entries, sort by value descending, limit(3), then map each entry to its key.
  4. Name the cost. Grouping is O(n). Sorting is O(k log k) for k customers. sorted must see every entry, so laziness does not help here.
  5. Check. Orders Ana 50, Ben 70, Ana 30, Cy 10, Di 40 give totals 80, 70, 40, 10: [Ana, Ben, Di].
record Order(String customer, long cents) {}

static List<String> topThree(List<Order> orders) {
    return orders.stream()
        .collect(Collectors.groupingBy(Order::customer, Collectors.summingLong(Order::cents)))
        .entrySet().stream()
        .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
        .limit(3)
        .map(Map.Entry::getKey)
        .toList();
}
Group, sort by total, keep three

How to answer

  • Intermediate operations return a Stream, so they chain; nothing runs until a terminal operation is called.
  • A terminal operation returns a value, an Optional or nothing, and closes the pipeline.
  • Elements flow one at a time through every stage, so short-circuiting operations like findFirst can stop early.
  • Stateful operations such as sorted and distinct must remember elements; stateless ones like filter and map do not.
  • A stream is single-use; build a new one from the source to run another pipeline.

Common mistakes

  • Saying filter or map processes the whole collection when called; nothing runs until a terminal operation.
  • Reusing a stream variable for a second terminal operation; it throws IllegalStateException.

Follow-up questions

What does it mean that streams are lazy?

Building a pipeline runs nothing: filter and map only record what to do. When the terminal operation asks for a result, elements are pulled from the source one at a time, and each runs through every stage before the next is read. That is why findFirst can stop after the first match and why a pipeline without a terminal operation never runs at all.

  • Intermediate operations record work; the terminal operation triggers it.
  • Each element passes through every stage before the next element is read.
  • Short-circuiting operations like findFirst, anyMatch and limit stop pulling once they have their answer.
  • A peek or lambda with a print shows the order in which elements are visited.
Optional<String> first = Stream.of("al", "bob", "cy", "dan")
    .peek(n -> System.out.println("visit " + n))
    .filter(n -> n.length() > 2)
    .map(String::toUpperCase)
    .findFirst();          // prints: visit al, visit bob
System.out.println(first); // Optional[BOB]

See it in the infographic: A lazy stream, one element at a time

What is the difference between map and flatMap?

map applies a function to each element and gives exactly one output per input, so a function that returns a list produces a stream of lists. flatMap expects the function to return a stream for each element and joins those streams into one, so the items come out flat. For orders whose items are [a, b], [c, d, e] and [], map gives 3 lists and flatMap gives 5 strings.

  • map: one input, one output, of any type.
  • flatMap: one input, a stream of zero or more outputs, all joined into one stream.
  • An empty list is still one element after map and adds nothing after flatMap.
  • Optional has the same pair: flatMap avoids an Optional<Optional<T>>.
List<List<String>> nested = orders.stream()
    .map(Order::items).toList();               // [[a, b], [c, d, e], []]
List<String> flat = orders.stream()
    .flatMap(o -> o.items().stream()).toList(); // [a, b, c, d, e]

See it in the infographic: map or flatMap on lists of items?

What is a functional interface, and which ones does the JDK (Java Development Kit) provide?

A functional interface has exactly one abstract method, so a lambda or method reference can implement it. Default and static methods, and abstract methods that redeclare Object methods such as equals, do not count. @FunctionalInterface makes the compiler check the rule. The JDK provides Predicate, Function, Supplier, Consumer, UnaryOperator and BiFunction in java.util.function, and older ones like Runnable and Comparator qualify too.

  • One abstract method; default and static methods are allowed.
  • @FunctionalInterface is optional, but it turns a second abstract method into a compile error.
  • Predicate<T> tests, Function<T, R> transforms, Supplier<T> creates, Consumer<T> accepts.
  • A method reference like String::toUpperCase is a shorter lambda for the same interface.
Predicate<String> longName = n -> n.length() > 2;
Function<String, String> upper = String::toUpperCase;
Supplier<List<String>> fresh = ArrayList::new;
System.out.println(longName.test("bob")); // true
System.out.println(upper.apply("bob"));   // BOB

See it in the infographic: A lazy stream, one element at a time

How is Optional commonly misused?

Optional is meant as a return type that says "there may be no result". It is misused when get() is called without checking, which throws NoSuchElementException on an empty Optional, when Optional.of(null) throws NullPointerException, or when it is used for fields, parameters or collections. orElse(expensive()) also runs expensive() even when a value is present; orElseGet runs it only when needed.

  • Use Optional as a return type, not for fields, parameters or collection elements.
  • get() on an empty Optional throws; prefer orElse, orElseGet, orElseThrow or map.
  • Optional.of(null) throws NullPointerException; use Optional.ofNullable for a value that may be null.
  • orElse(x) always evaluates x; orElseGet(() -> x) evaluates it only for an empty Optional.
  • Return an empty collection, not an Optional of a collection.
Optional<String> name = Optional.of("bob");
name.orElse(expensive());          // expensive() runs anyway
name.orElseGet(() -> expensive()); // expensive() does not run
Optional.ofNullable(null);         // Optional.empty
Optional.of(null);                 // NullPointerException

See it in the infographic: map or flatMap on lists of items?

When should you use a parallel stream?

Rarely, and only after measuring. parallel() splits the work across the common ForkJoinPool, whose default parallelism is one less than the number of processors and which the whole JVM (Java Virtual Machine) shares. It can help CPU-heavy work on large, easily split sources with no shared state. It hurts with small inputs, blocking calls, and lambdas that write to shared collections, which can lose elements.

  • Parallel streams run on the common ForkJoinPool, shared with every other parallel stream in the JVM.
  • They pay off for large, CPU-bound, stateless work on sources like arrays and ArrayList.
  • Never add to a shared ArrayList from forEach; collect with toList() or collect instead.
  • forEachOrdered and toList() keep encounter order; forEach does not.
  • Measure before and after; the split and merge overhead often outweighs the gain.
List<Integer> unsafe = new ArrayList<>();
IntStream.range(0, 100_000).parallel()
    .forEach(unsafe::add);           // can lose elements
List<Integer> safe = IntStream.range(0, 100_000).parallel()
    .boxed().toList();               // 100000 elements, in order

See it in the infographic: A lazy stream, one element at a time

Can a stream be reused?

No. After a terminal operation the stream is consumed, and calling another operation on it throws IllegalStateException: "stream has already been operated upon or closed". Keep the source, such as the List, and call stream() again, or pass a Supplier<Stream<T>> when the same pipeline must run more than once.

Why must a local variable used in a lambda be effectively final?

A lambda captures the value of a local variable, not the variable itself, and it may run later or on another thread. Java only allows capturing locals that are final or never reassigned, so the copy cannot go stale. count++ inside forEach fails with "local variables referenced from a lambda expression must be final or effectively final"; use count() or a reduction instead.

What is a stateful operation, and why does it matter?

A stateful intermediate operation needs to remember elements it has seen: sorted must read every element before it can emit the first, and distinct keeps the elements seen so far. So sorted().findFirst() reads the whole source even though it returns one element, and stateful steps cost memory and limit parallel speed-up.

Check yourself

1. What does this code print?
Stream.of("al", "bob", "cy", "dan")
    .peek(n -> System.out.println(n))
    .filter(n -> n.length() > 2)
    .findFirst();
Show answers
  • al and bob: Correct. Elements are pulled one at a time, and findFirst() stops as soon as bob passes the filter.
  • al, bob, cy and dan: Incorrect. The stream is lazy; cy and dan are never read once findFirst() has its match.
  • Nothing: Incorrect. findFirst() is a terminal operation, so the pipeline runs and peek prints what it visits.
2. A pipeline calls filter and map but no terminal operation. What runs?
Show answers
  • Nothing; no element is read: Correct. Intermediate operations are lazy and only run when a terminal operation pulls elements.
  • The filter, on every element: Incorrect. filter is intermediate too, so it waits for a terminal operation like everything else.
  • Every stage, on every element: Incorrect. Without a terminal operation nothing asks for elements, so no stage runs.
3. Three orders have the items [a, b], [c, d, e] and []. What does orders.stream().flatMap(o -> o.items().stream()).count() return?
Show answers
  • 5: Correct. flatMap joins the items of every order into one stream, and the empty order adds none.
  • 3: Incorrect. That is map, which keeps one element, a List, per order.
  • 6: Incorrect. An empty list adds no elements to a flatMap result, not one.