Stream.ofNullable()
Create a zero-or-one element stream from a nullable value.
Porównanie kodu
✕ Java 8
Stream<String> s = val != null
? Stream.of(val)
: Stream.empty();
✓ Java 9+
Stream<String> s =
Stream.ofNullable(val);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Null Check
Nowoczesne podejście
ofNullable()
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Stream.ofNullable()
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
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.
Powiązana dokumentacja