Home » Java » Collections.max function for iterable<Integer> in java

Collections.max function for iterable<Integer> in java

Posted by: admin December 28, 2021 Leave a comment

Questions:

The Java Collections.max takes only a collection of a sortable object. However since the collection is not necessarily sorted, I don’t see any reason not to implement the same max function for iterable types.

Is there a max method for Iterable<T extends Comparable<? super T>> in java’s standard library?

Answers:

While Guava is not Java’s standard library, it’s close enough…

E com.google.common.collect.Ordering#max(Iterable<E> iterable)

e.g. T max = Ordering.natural().max(myIterable);

As to why the standard library does not implement it, it may be because a Collection must be finite, but an Iterable need not be—and, arguably, one should never accept an Iterable if a non-terminating Iterable would cause your code to loop forever.

###

Collections.max was introduced in 1.2. Iterable was introduced in 1.5.

It’s rare to have an Iterable that is not a Collection. If you do then it’s straightforward to implement (be careful to read the spec). If you think it is really important you can submit an RFE on bugs.sun.com (or vote if there is already one there).

###

Hmm… no, there isn’t. If you want to use Collections.max() you have to convert your Iterable into a Collection first, probably by adding all of the elements into a List (or Set, depending on the data).

###

By definition the elements of the collection must be “sortable” (specifically, they must implements Comparable) since in order to compute the maximum, it must be possible to work out whether one element is greater than another (which is exactly what Comparable means).

The max() method in the Collections class has essentially the exact type signature you posted there, so it should suit your purpose.