如何从列表中检索所有最大值?

use*_*111 3 java collections list max comparable

我有一个叫做Employee实现Comparable接口的类.

现在Employee我的列表中有5个对象,每个对象都有自己的salary属性.我想找到所有Employee具有最高工资的对象.

我可以使用单个对象

 Employee employee = Collections.max(employeeList);
Run Code Online (Sandbox Code Playgroud)

但是这只返回一个Employee,而我正在尝试检索具有相同最大值的所有对象的数组或列表.我怎样才能做到这一点?

JB *_*zet 7

为了提高效率,您应该遍历列表并自己查找所有最大元素:

List<Employee> result = new ArrayList<>();
Employee currentMax = null;
for (Employee e : list) {
    if (currentMax == null || e.compareTo(currentMax) > 0) {
        currentMax = e;
        result.clear();
        result.add(e);
    }
    else if (currentMax!= null && e.compareTo(currentMax) == 0) {
        result.add(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

该解决方案是O(n),并且需要单次通过列表.