Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?/)

like image 704
Manikandan Kbk DIP Avatar asked Sep 08 '26 23:09

Manikandan Kbk DIP


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

like image 160
Eran Avatar answered Sep 11 '26 13:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!