The Stream.ofNullable method in Java is a utility introduced in Java 9. It is used to create a stream from an object that may or may not be null. This is especially useful when dealing with optional values where you want to avoid manually checking if a value is null before creating a stream.
Here’s how Stream.ofNullable works:
- If the passed object is not null, it creates a stream containing that single element.
- If the passed object is null, it creates an empty stream.
This is particularly effective when you need to safely process nullable values in a stream pipeline without additional null checks.
Syntax:
Stream.ofNullable(T t)
Parameters:
t: The object that you want to create a stream from (nullable).
Returns:
- A stream consisting of the specified element if it is non-null.
- An empty stream if the element is null.
Example Usage:
Basic Example
package org.kodejava.util.stream;
import java.util.stream.Stream;
public class StreamOfNullableExample {
public static void main(String[] args) {
String value = "Hello, World!";
Stream<String> stream1 = Stream.ofNullable(value);
stream1.forEach(System.out::println); // Outputs: Hello, World!
String nullValue = null;
Stream<String> stream2 = Stream.ofNullable(nullValue);
stream2.forEach(System.out::println); // Outputs nothing (empty stream)
}
}
Combining with Other Stream Operations
package org.kodejava.util.stream;
import java.util.stream.Collectors;
import java.util.List;
import java.util.stream.Stream;
public class OptionalStreamExample {
public static void main(String[] args) {
String[] values = { "one", null, "three", null };
// Collect all non-null values into a list
List<String> nonNullValues = Stream.of(values)
.flatMap(Stream::ofNullable) // Process each value safely, handling nulls
.collect(Collectors.toList());
System.out.println(nonNullValues); // Outputs: [one, three]
}
}
Practical Example with Optional
When dealing with Optional values, you can use Stream.ofNullable to easily integrate with other streams.
package org.kodejava.util.stream;
import java.util.Optional;
import java.util.stream.Stream;
public class OptionalToStreamExample {
public static void main(String[] args) {
Optional<String> optionalValue = Optional.of("Hello, Optional!");
// Convert Optional to Stream and process
Stream<String> stream = Stream.ofNullable(optionalValue.orElse(null));
stream.forEach(System.out::println); // Outputs: Hello, Optional!
}
}
Key Highlights of Stream.ofNullable:
- Avoids the need for null checks when creating streams for nullable values.
- Simplifies stream pipelines where null handling is required.
- Works well with
flatMapto filter null values while processing arrays, collections, or optionals.
By using Stream.ofNullable, you can write cleaner, safer, and more concise code when dealing with nullable values in streams.
