Streams: Optional.stream() drops the empties

Java 9's Optional.stream() turns a lookup that may fail into a stream of zero or one element, so flatMap quietly skips the misses.

Code
var index = Map.of("a", 1, "c", 3);
Function<String, Optional<Integer>> lookup = k -> Optional.ofNullable(index.get(k));

List<Integer> found = Stream.of("a", "b", "c", "d")
        .map(lookup)
        .flatMap(Optional::stream)
        .sorted()
        .toList();

System.out.println("found = " + found);
System.out.println("Stream.ofNullable(null).count() = " + Stream.ofNullable(null).count());
Output
found = [1, 3]
Stream.ofNullable(null).count() = 0
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30