Stream.ofNullable()
Create a zero-or-one element stream from a nullable value.
Code Comparison
✕ Java 8
Stream<String> s = val != null
? Stream.of(val)
: Stream.empty();
✓ Java 9+
Stream<String> s =
Stream.ofNullable(val);
Why the modern way wins
Concise
One call replaces the ternary conditional.
Flatmap-friendly
Perfect inside flatMap to skip null values.
Null-safe
No NPE risk — null becomes empty stream.
Old Approach
Null Check
Modern Approach
ofNullable()
Since JDK
9
Difficulty
beginner
JDK Support
Stream.ofNullable()
Available
Widely available since JDK 9 (Sept 2017)
How it works
Stream.ofNullable() returns a single-element stream if the value is non-null, or an empty stream if null. Eliminates the ternary null check pattern.