Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.max function for iterable<Integer> in java

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?

like image 522
Elazar Leibovich Avatar asked Jan 14 '09 17:01

Elazar Leibovich


2 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.

like image 113
Alice Purcell Avatar answered Oct 22 '22 04:10

Alice Purcell


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

like image 5
Tom Hawtin - tackline Avatar answered Oct 22 '22 04:10

Tom Hawtin - tackline