使用预定义的比较器在Java中查找最大值

rip*_*234 4 java functional-programming

我有一个List<Foo>和一个compare()方法接受两个Foo对象并返回'更大'对象.是否有内置的Java方法获取列表并找到最大的一个?

Mic*_*ers 27

如果Foo实现Comparable<Foo>,那么Collections.max(Collection)你正在寻找.

如果没有,您可以创建一个Comparator<Foo>并使用Collections.max(Collection, Comparator).

// 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;
    }
});
Run Code Online (Sandbox Code Playgroud)


Ben*_*n S 8

是的,List是Collection的子类,因此您可以使用max方法.