sum return type for primitive streams

Brian Goetz brian.goetz at oracle.com
Fri Feb 1 07:07:35 PST 2013


That is correct behavior.

The integers form a monoid under +, whose identity is zero.  Therefore, 
there is a sensible result value when there are no elements to sum.

The min/max operations on integers, on the other hand, have no sensible 
identity value.  If we picked one (e.g., have min() return 
Integer.MAX_VALUE), we would be unable to distinguish between the result 
of min'ing no elements and min'ing a list that happened to contain only 
that distinguished value.  (This is the problem that Map.get() has -- 
when you get null, you don't know whether there's no mapping or the key 
is mapped to null.)

There were some who suggested we do this anyway.  There were others who 
suggested we force the user to pass in their "poison" value to min/max. 
  In the end, we use Optional where we must, and avoid Optional where we 
can.

On 2/1/2013 9:43 AM, Georgiy Rakov wrote:
> Hello,
>
> IntStream sum method return type is a primitive while the return type of
> min, max, average is Optional...:
>
>           default long sum() {
>               return collect(Collectors.intSumAsLong()).sum();
>           }
>
>           default OptionalInt min() {
>               return reduce(Math::min);
>           }
>
>           default OptionalInt max() {
>               return reduce(Math::max);
>           }
>
>           default OptionalDouble average() {
>               return collect(Collectors.intCountAndSumAsLong()).mean();
>           }
>
> Could you please tell if it's a bug or expected behavior. If it's
> expected behavior could you please clarify why it is because from the
> first glance OptionalLong should be the return type for sum method.
>
> The same is true for DoubleStream and LongStream.
>
> Thank you, Georgiy.
>


More information about the lambda-dev mailing list