Streams Początkujący

Create a zero-or-one element stream from a nullable value.

✕ 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ć.
📏

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
Stream.ofNullable()
Dostępne

Widely available since JDK 9 (Sept 2017)

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.

Udostępnij 𝕏 🦋 in