How to convert an Optional<T> into a Stream<T>?

slartidan picture slartidan · Nov 26, 2015 · Viewed 17.4k times · Source

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

Answer

slartidan picture slartidan · Nov 26, 2015

If restricted with Java-8, you can do this:

Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);