Home > Back-end >  Readable Way for Optional<Stream> to Stream
Readable Way for Optional<Stream> to Stream

Time:11-13

Suppose you have an Optional Stream.

Optional<Stream<Integer>> optionalStream = Optional.of(Stream.of(1, 2, 3));

Now you want to have the stream itself. If the Optional is empty you want to get an empty Stream. Is there a more beautiful way than doing this:

Stream<Integer> stream = optionalStream.stream().flatMap(Function.identity());

What I think of is something like flatStream().

CodePudding user response:

Use Stream.empty()

It doesn't make sense to wrap a Stream with an Optional.

An Optional allows to interact safely with the result of the method call, which might not produce the data. And empty Optional represents the case when the data is absent.

A Stream can also be empty, and it represents the absents of data perfectly fine without a need of being packed into an Optional.

Use Stream.empty() as a return value for your method.

You also might want to check these references:

CodePudding user response:

I guess you could use the orElseGet() method:

optionalStream.orElseGet(()->Stream.empty())
  • Related