Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does the minBy() returns Optional but others dont?

My question is why the Collectors.minBy () method returns an Optional, but the Collectors.summingInt () or Collectors.averagingInt () method does not return an Optional? Is it not possible that the stream is empty when these methods are called?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading