I have a List<Foo>
, and a compare() method taking two Foo objects and returning the 'greater' one. Is there a built-in Java method that takes the list and finds the largest one?
views:
313answers:
6
+8
A:
Yes, the List is a subclass of Collection and so you can use the max method.
Ben S
2009-11-03 18:36:00
+14
A:
If Foo
implements Comparable<Foo>
, then Collections.max(Collection)
is what you're looking for.
If not, you can create a Comparator<Foo>
and use Collections.max(Collection, Comparator)
instead.
Example
// Assuming that Foo implements Comparable<Foo>
List<Foo> fooList = ...;
Foo maximum = Collections.max(fooList);
// Normally Foos are compared by the size of their baz, but now we want to
// find the Foo with the largest gimblefleck.
Foo maxGimble = Collections.max(fooList, new Comparator<Foo>() {
@Override
public int compare(Foo first, Foo second) {
if (first.getGimblefleck() > second.getGimblefleck())
return 1;
else if (first.getGimblefleck() < second.getGimblefleck())
return -1;
return 0;
}
});
Michael Myers
2009-11-03 18:36:34
A:
Take a look at Google Collections - they have lots of methods that help you do this sort of thing using Predicates.
Fortyrunner
2009-11-03 19:55:50
A:
Take a look at lambdaj as well. There are lots of feature to manipulate collection in a functional style.
Mario Fusco
2009-11-07 15:17:11