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
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.
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
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.
You can do:
Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
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"))
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)