Java 11 introduced a convenient and null-safe method for stream creation: Stream.ofNullable(T t)
. This method allows developers to create a stream with a single element if itโs non-null, or an empty stream if the value is null.
This enhancement reduces boilerplate code and minimizes the risk of NullPointerException
when working with optional or uncertain values in the Stream API.
๐ Overview: Stream.ofNullable()
java
Stream.ofNullable(T t)
- Returns:
- A stream of one element if
t
is not null
- An empty stream if
t
is null
๐ Why Use ofNullable()
?
Before Java 11, handling nullable objects with streams was verbose:
java
Stream<String> stream = myObject != null ? Stream.of(myObject) : Stream.empty();
Java 11 simplifies this with:
java
Stream<String> stream = Stream.ofNullable(myObject);
Cleaner, safer, and easier to read.
๐ป Example Code
java
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String element = "Hello";
Stream<String> stream = Stream.ofNullable(element);
stream.forEach(System.out::println); // Outputs: Hello
String nullElement = null;
Stream<String> emptyStream = Stream.ofNullable(nullElement);
emptyStream.forEach(System.out::println); // Outputs nothing
}
}
โ
Output:
nginx
Hello
๐ง Use Cases
- Null-safe filtering: Avoid
NullPointerException
during stream processing - Conditional flatMap: Return a stream from an optional value
- Data transformation pipelines: Ensure nulls donโt break the flow
๐ Summary
FeatureBenefitStream.ofNullable()
Create stream from single elementHandles null safelyReturns empty stream if nullIntroduced inJava 11
Java 11โs Stream.ofNullable()
method is a small but powerful addition for developers working with the Stream API. It ensures null safety, reduces code noise, and helps you write cleaner, more robust Java code.