Reputation: 21576
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
Upvotes: 77
Views: 31073
Reputation: 621
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));
Upvotes: 1
Reputation: 21576
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
Upvotes: 150
Reputation: 100209
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.
Upvotes: 83
Reputation: 9776
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)
Upvotes: 0
Reputation: 12826
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.
Upvotes: 1
Reputation: 7725
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"))
Upvotes: 8
Reputation: 62864
You can do:
Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
Upvotes: 8