How to convert an Optional<T> into a Stream<T>?
21,733
Solution 1
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 2
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
Solution 3
You can do:
Stream<String> texts = optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
Solution 4
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
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.
Comments
-
slartidan almost 2 years
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
-
slartidan over 8 yearsI'm not a big fan of
isPresent
, it feels like a legacy method to me and reminds me of the times before Java8. But thanks for providing an alternative solution. -
Paul FREAKN Baker over 6 yearsI upvoted this because Java 9 has some non-backward compatible changes for some projects in their current state. Some projects, such as lombok, are part of core corporate artifacts that are slow to be changed.
-
augurar almost 6 yearsLess fluent than the
map().orElseGet()
approach but probably slightly more efficient. -
walen over 4 yearsIf by any chance your optional happens to contain a
List<String>
instead of a singleString
object, you just need to replaceStream::of
withList::stream
. The same applies to any other type of collection. You can also just useCollection::stream
. Else you will get aStream<List<String>>
which is probably not what you wanted. -
Naman over 3 years@walen the question is to convert an
Optional<T>
toStream<T>
if the T isList<String>
, so be it. The answer stands correct still. What you might be looking for is flattening the collection. Aside, you are already on the wrong path if you have ended up usingOptional<Collection<T>>
. -
walen over 3 years@Naman No need to justify the answer — I didn't say it wasn't correct. I just gave a tip on how to apply this solution to an
Optional
containing aList
, which is a scenario some people might encounter.