Reputation: 362
My question is why the Collectors.minBy()
method returns an Optional
, but the Collectors.summingInt()
and Collectors.averagingInt()
methods do not return an Optional
? Is it not possible that the stream is empty when these methods are called?
Upvotes: 3
Views: 543
Reputation: 339362
Logically, you cannot have a minimum or maximum if the collection is empty. Returning an empty Optional
is appropriate when no legitimate value is possible.
In contrast, one could argue that a sum of no elements (empty collection) is zero, zero meaning “nothing” numerically. If I have no apples, and I add to that an empty bag of no apples, how many apples do I have? Zero; the sum of nothing is zero.
Ditto for average. If I have three empty bags, the average count of apples per bag is zero.
However, I acknowledge that reasonable people could disagree, especially in certain contexts. I do not know what a mathematician world say. But I do believe the common businessperson would expect zero in both cases.
Note that the Javadoc clearly states: “If no elements are present, the result is 0.”. In the end, all that matters is what behavior the Javadoc promises. If that behavior does not match your expectations, replace your use of that class with another class that does, or write your own.
Upvotes: 2