繁体   English   中英

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

[英]How can I retrieve all of the maximum values from a list?

我有一个名为Employee的类,它实现了Comparable接口。

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

我可以使用单个对象

 Employee employee = Collections.max(employeeList);

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

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

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);
    }
}

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

试试这个:

Collections.sort(list);
Collections.reverse(list);
Set<Employee> highest = new HashSet<Employee>();
Employee max = list.get(0);
for (Employee employee : list) {
    if (e.compareTo(max) < 0) break;
    highest.add(employee);
}

我选择了一个Set,因为不应该有重复。

Employee max=Collections.max(employeeList);
List <Employee> maxEmployeeList=new ArrayList<Employee>();
maxEmployeeList.add(max);
for(Employee e:employeeList){
  if(e.equals(max)){
   maxEmployeeList.add(e);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM