How to convert an Optional<T> into a Stream<T>?
JavaJava 8Java StreamOptionalJava Problem Overview
I want to prepend a stream with an Optional. Since Stream.concat
can only concatinate Streams I have this question:
How do I convert an Optional<T> into a Stream<T>?
Example:
Optional<String> optional = Optional.of("Hello");
Stream<String> texts = optional.stream(); // not working
Java Solutions
Solution 1 - Java
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
Solution 2 - Java
In Java-9 the missing stream()
method is added, so this code works:
Stream<String> texts = optional.stream();
See JDK-8050820. Download Java-9 here.
Solution 3 - Java
You can do:
Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
Solution 4 - Java
I can recommend Guava's Streams.stream(optional)
method if you are not on Java 9. A simple example:
Streams.stream(Optional.of("Hello"))
Also possible to static import Streams.stream
, so you can just write
stream(Optional.of("Hello"))
Solution 5 - Java
If you're on an older version of Java (lookin' at you, Android) and are using the aNNiMON Lightweight Stream API, you can do something along the lines of the following:
final List<String> flintstones = new ArrayList<String>(){{
add("Fred");
add("Wilma");
add("Pebbles");
}};
final List<String> another = Optional.ofNullable(flintstones)
.map(Stream::of)
.orElseGet(Stream::empty)
.toList();
This example just makes a copy of the list.
Solution 6 - Java
A nice library from one of my ex collegues is Streamify. A lot of collectors, creating streams from practicly everything.
https://github.com/sourcy/streamify
Creating a stream form an optional in streamify:
Streamify.stream(optional)
Solution 7 - Java
It can depend of how you want to convert empty optional to stream element. If you want to interpret it as "nothing" (or "no element"):
Stream<String> texts = optional.stream(); // since JDK 9
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty); // JDK 8
But if you want to interpret it as null:
Stream<String> texts = Stream.of(optional.oreElse(null));