java.util.Optional fields

Aleksey Shipilev aleksey.shipilev at oracle.com
Fri Sep 21 07:34:51 PDT 2012


On 09/21/2012 05:44 PM, Peter Levart wrote:
> When I see where it's used in Stream, for example:
> 
>      Optional<T> findFirst();
> 
> I can only imagine that it's purpose was to allow null values as 
> elements of streams. That is, it allows to differentiate between a 
> not-present (elements of a stream) and an element of 'null'...
> 
> An alternative of throwing NoSuchElementException was replaced by 
> returning an Optional.

Having Optional enables me to do fluent API thingies like:
  stream.getFirst().orElseThrow(() -> new MyFancyException())

I would speculate *this* was the intended goal for Optional.

-Aleksey.



More information about the lambda-dev mailing list