Find max value in Java with a predefined comparator
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?
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;
}
});
Yes, the List is a subclass of Collection and so you can use the max method.
try java.util.Collections.max
Use Collections#max(Collection)
.
Assuming Foo
is not an inner class and compare()
method exists in a class named CompareClass
You can do the following:
Collections.max(fooList, CompareClass::compare);
Which gives the fooList
and the method compare
as inputs to Collections.max()
and returns the Foo
object with the max value - according to your compare method.
Take a look at Google Collections - they have lots of methods that help you do this sort of thing using Predicates.
Take a look at lambdaj as well. There are lots of feature to manipulate collection in a functional style.
精彩评论