Stream.ofNullable produces an empty stream for null and a single-element stream otherwise, which combines with flatMap to drop nulls from a stream of streams without a manual null check.
String maybeNull = null;
String present = "value";
long countNull = Stream.ofNullable(maybeNull).count();
long countPresent = Stream.ofNullable(present).count();
System.out.println("Count from null: " + countNull);
System.out.println("Count from present: " + countPresent);
List<String> flattened = Stream.of("a", null, "b")
.flatMap(Stream::ofNullable)
.toList();
System.out.println("Nulls dropped in flatMap: " + flattened);
Count from null: 0
Count from present: 1
Nulls dropped in flatMap: [a, b]
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-09-27