list.stream().map(Foo::getAttr)
... null.
JavaDoc findAny() ( findFirst()) :
:
a , , empty ,
:
NullPointerException - null
, findAny() , : , , NullPointerException.
, Optional ( JavaDoc, ):
,
... , , Optional.ifPresent( x -> x.method()) NullPointerException - , x .
findAny() Optional.of(null). Optional.empty() , , , .
Many parts of the infrastructure Stream/ are Optionalaimed at preventing the use of zeros.
You can get around this by matching nulls with Optionalsto get Optional<Optional<Foo>>- which looks a bit confusing but is an accurate representation of your domain. Optional.empty()means the stream is empty. Optional.of(Optional.empty())means he found one empty element:
list.stream().map(Foo::getAttr).map(Optional::ofNullable).findAny()
source
share