Issue
Suppose I have an Optional
containing a Stream
:
Optional<Stream<Integer>> optionalStream = Optional.of(Stream.of(1, 2, 3));
Now I need to extract the Stream
itself. If the Optional
is empty, you want to get an empty Stream.
I'm looking of is something like flatStream()
that performs transformation in one step. How can I do this?
My current attempt:
Stream<Integer> stream = optionalStream.stream().flatMap(Function.identity());
The Context of the Problem
In my real scenario, I have something like this, which gives me a Stream<Optional<Foo>>
:
stream.findFirst().map(e -> e.getChildren())
Solution
I guess you could use the orElseGet()
method:
optionalStream.orElseGet(()->Stream.empty())
Answered By - Julio César Estravis
Answer Checked By - Robin (JavaFixing Admin)