Primitive streams and optional

Paul Sandoz paul.sandoz at oracle.com
Wed Nov 21 00:48:10 PST 2012


I don't like the approach of some IntStream methods overloaded to take defaults and throw exceptions.

There is no way no way to detect before hand if the stream is empty or not. There is no clear differentiation between the default and a value.

I prefer the use of Optional<Integer>. I could live, begrudgingly, with OptionalInt, but i don't think there is a strong technical requirement for it.

We don't have to overload the methods and one can do min().orElseThrow(). There is a clear distinction between a value and a default. It's more consistent with Stream.

Paul.

On Nov 20, 2012, at 11:14 PM, Brian Goetz <brian.goetz at Oracle.COM> wrote:

> We're working through implementing the primitive specialization of streams now.  So far, its pretty straightforward; many of the ops on reference streams have an obvious analogue (e.g., filter, map, forEach), and many are just not applicable (e.g., into, since there are no primitive collections.)  There are also a number of additional methods that make sense on primitive streams, such as sum().  (You can see the work in progress in the lambda repo.)
> 
> The tricky ones are the ones that return some sort of Optional.  For sum() there is an obvious value to return if there are no elements in the stream (zero), but for min/max/average, it would require more distortion to avoid optionality.  We can't expect users to know a priori whether the stream is empty.  Example:
> 
> int firstOrderNumber
>  customers.flatMap(c -> /* c.orders */)
>           .map(o -> o.getOrderId())
>           .min();
> 
> The options are:
> 
> - throw NSEE
> - make up a bad default (e.g., MAX_VALUE for min)
> - return an Optional<Integer>
> - return an OptionalInt
> 
> The first two are pretty bad, and are asymmetric to the reference streams.  Creating N new OptionalXxx classes is kind of annoying and bloaty.  (There's an argument to be made for "Well, we're boxing once at the end anyway, boxing twice with Optional<Integer> isn't terrible.") Though I suspect that will be an ongoing irritant.  Are there other "options"?



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