views:

313

answers:

6

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?

+8  A: 

Yes, the List is a subclass of Collection and so you can use the max method.

Ben S
+3  A: 

try java.util.Collections.max

meriton
+3  A: 

Use Collections#max().

BalusC
+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
A: 

Take a look at Google Collections - they have lots of methods that help you do this sort of thing using Predicates.

Fortyrunner
A: 

Take a look at lambdaj as well. There are lots of feature to manipulate collection in a functional style.

Mario Fusco