Streams: Stream.ofNullable turns a possibly-null value into 0 or 1 elements

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.

Code
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);
Output
Count from null: 0
Count from present: 1
Nulls dropped in flatMap: [a, b]
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms