如何转换可选的<T>进入 Stream <T>?

2022-01-22 00:00:00 java-8 java optional java-stream

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();

See JDK-8050820. Download Java-9 here.

相关文章