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
In Java-9 the missing stream() method is added, so this code works: Stream<String> texts = optional. stream();
The stream() method of java. util. Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream.
In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
If restricted with Java-8, you can do this:
Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With