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());
In my real scenario, I have something like this, which gives me a Stream<Optional<Foo>>
:
stream.findFirst().map(e -> e.getChildren())
I guess you could use the orElseGet()
method:
optionalStream.orElseGet(()->Stream.empty())