sum return type for primitive streams

Ali Lahijani alahijani at gmail.com
Fri Feb 1 08:00:08 PST 2013

```On Fri, Feb 1, 2013 at 6:37 PM, Brian Goetz <brian.goetz at oracle.com> wrote:

> 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.

Sorry to bring it up again, but integers also form a monoid under min, max.
With Integer.MIN_VALUE and Integer.MAX_VALUE being the obvious identities.

Actually much better: they form a semi-lattice (a commutative and
idempotent monoid).
And the two operations are dual to each other, so they even form a
commutative lattice.

> 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.)
>

This is absolutely no different from sum (at least in principle).
We are unable to distinguish between the result of summing no elements and
summing a list that happened to contain only zeros.

Contrast this with average() which is not defined on an empty list because
that would involve division by zero.

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.
> >
>
>
Best
Ali
```