Joe Bowbeer joe.bowbeer at
Tue Sep 25 05:25:42 PDT 2012

No one would write that code. They would add a filter to remove nulls, or
to replace nulls with None, or to replace null with another value, and then
invoke findAny. Or they would invoke the version of findAny (is there one?)
that replaces null with a default value.

When I think of ignoring nulls in streams, I think of zipWithIndex, and
then I reconsider.
On Sep 25, 2012 4:38 AM, "Doug Lea" <dl at> wrote:

> On 09/24/12 20:10, Brian Goetz wrote:
>> Your disbelief is well-founded, since that's not what is being suggested.
>>  What
>> we're suggesting is that findAny (or, more precisely, the Optional
>> constructor
>> called by findAny) could throw NPE if the stream contains a null, even if
>> the
>> stream also contains a non-null.  So the spec looks more like:
>>    @return an absent Optional if the stream is empty, or a present
>>    optional containing a selected element from the stream
>>    @throw NPE if the selected element of the stream is null
> Which does make findAny null-aware. And in a less than helpful
> way, because if a user gets NPE, then they know that the predicate
> DOES hold for at least one element (null).
> As usual, my main concern is about impact on composition
> (aka modular reasoning). Any general-purpose
> higher-level utility using findAny without knowing
> if the source may include nulls will need to do
> something like:
>   boolean present;
>   T x;
>   try {
>        Optional<T> r = ...findAny(...);
>        if (present = r.isPresent()) x = r.get();
>   } catch(NPE ex) {
>       present = true;
>       x = null;
>   }
> Not very nice.
> I hate to be a pest about this, but the only choices
> I know that compose at all remain:
> 1. All stream ops throw NPE on any null element
> 2. All stream ops ignore nulls.
> 3. No use of Optionals; rely only on valueIfAbsent constructions
> And of these, choice (2) still seems most defensible.
> -Doug

More information about the lambda-libs-spec-observers mailing list