Why does Java8 Stream.min() and max() takes comparator as input?

Viewed 202

Isn't it obvious that min() function should compute the minimum element in the collection and return us the data?

I can accept the fact for User defined objects like Person, Animal etc... we have to provide comparator to compute the min element. But for universally accepted types like Integer, String, Double why does it try to accept comparator implementation.

It could have been overloaded functions like?

1.

min() => Just for types like Integer, String, Double etc..

2.

min(Comparator c) => for types like user defined objects like Person etc...

eg.,

List<Integer> list = new ArrayList<>();

The fact that list.stream().min(/I can still pass a comparator that computes maximum Integer data and breach the underlying intent of the function right?/)

3 Answers

The only way min() could work without a Comparator was if the element type T of the Stream<T> was bound to implement Comparable<T>.

However, the Stream interface should support both element types that implement Comparable and element types that don't. Therefore, you must pass a Comparator<T> to min().

There is no way to provide a method only when it is a stream of Comparable instances. All instances of stream have to have the same methods.

Thats because the general Stream class cannot extinguise between primitive types and their Object counterparts (what to do with an empty/null ellement list?). The IntStream (and other primitive stream types) does have that functionality. E.g.

List<Integer> list;
list.stream().mapToInt(I -> I).min(); // max();

Hope this gives you a perspecitve on this.

Related