Doug Lea dl at
Tue Sep 25 04:37:48 PDT 2012

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.


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