Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...