views:

1050

answers:

3

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?

A: 

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

Bombe
A: 

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.

Andrzej Doyle
I want to compute the max of an Iterable which is not a Collection
Elazar Leibovich
+3  A: 

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

Tom Hawtin - tackline
Implementing an Iterable is implementing two functions, implementing a collection is more than double the work. So if I want to make a quick iterable of a class I created it's much easier.
Elazar Leibovich
Collections.max(new ArrayList<X>(0) { @Override public Iterator<X> iterator() { return iterable.iterator(); }});)
Tom Hawtin - tackline