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:
Addressing the Question-update
The best solution to the problem is to eliminate the problem.
The spirit of the answer remains unchanged: don't create an Optional<Stream<T>>
and there would be no need to deal with it.
Java 9 Optional.stream()
comes to the rescue. Apply stream()
after findFirst()
, and you would get either a singleton-stream containing a value captured by findFirst()
, or an empty stream. And then you can perform any transformation you need.
So, instead of this:
stream.findFirst().map(e -> e.getChildren())
Do the following:
stream.findFirst().stream().flatMap(Foo::getChildren)
Stream.limit()
Alternatively, as suggested by @Holger instead of findFirt()
you can apply limit(1)
and continue to chain stream-operation. This approach would work with JDK 8.
stream.limit(1).flatMap(Foo::getChildren)