Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 483
slartidan Avatar asked Nov 26 '15 15:11

slartidan


People also ask

How do you change from optional to streaming?

In Java-9 the missing stream() method is added, so this code works: Stream<String> texts = optional. stream();

What does the stream method on optional do?

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.

How do you cast optional to string?

In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .


1 Answers

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

Stream<String> texts = optional.map(Stream::of).orElseGet(Stream::empty); 
like image 174
slartidan Avatar answered Sep 18 '22 16:09

slartidan