简体   繁体   中英

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

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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