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

痞子三分冷 提交于 2021-02-05 06:19:05

问题


I have a class called Employee that implements the Comparable interface.

Now I have 5 Employee objects in my list, each of which has its own salary property. I want to find all of the Employee objects that have the max salary.

I can get a single object using

 Employee employee = Collections.max(employeeList);

but that only returns a single Employee, while I am trying retrieve an array or list of all of the objects with the same max value. How can I do this?


回答1:


To be efficient, you should iterate through the list and find all the max elements by yourself:

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

This solution is O(n), and requires a single pass through the list.




回答2:


Try this:

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

I chose a Set because there should be no duplicates.




回答3:


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


来源:https://stackoverflow.com/questions/18299087/how-can-i-retrieve-all-of-the-maximum-values-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!