Is there anything like Collections.max
which finds the maximal value in an array for regular arrays in the standard java runtime library?
views:
2528answers:
5As far as I know, no. You could look at asList (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#asList(T...)), but it's probably not worth it.
You could use Arrays.sort(int[]) and then access the first (or last) element of it. Or you could simply iterate over the array and look for the largest/biggest element. That’s basically a no-brainer.
No, there is no Arrays.max or a lookalike, at least in Java 6.
If you look at the signature and implementation of Collections.max, it makes quite heavy use of parameterized types. In Java, generic arrays are problematic to say the least, so maybe therefore it is not a good idea to provide a generic max implementation for arrays in Java, and keep the focus on (generic) collections.
Edit: as newacct correctly points out, the usage of generic arrays is not necessarily more problematic than the usage of generic collections, so I've edited the above text since the original was wrong. Still, the main argument of "generic arrays are problematic" is still valid in my opinion, and collections should be preferred over reference type arrays.
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
if (comp==null)
return (T)max((Collection<SelfComparable>) (Collection) coll);
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) > 0)
candidate = next;
}
return candidate;
}
You could also create a decorator for Collection which contains extra methods like getMaximumValue() and make it update the value returned every time element is added/removed if there's need.
This would only make sense though if you'd use the maximum value a lot in your program which would mean that iterating through the list every time would cause significant overhead.
If you have an array of Objects you can use
Collections.max(Arrays.asList(array));
If you have an array of primitive you can just use a simple loop.
long[] array;
long max = array[0];
for(long l : array) if (max < l) max = l;