How to convert an Optional<T> into a Stream<T>?
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
Solution 1:
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
Solution 2:
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.