user1585111
user1585111

Reputation: 1019

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?

Upvotes: 3

Views: 6586

Answers (3)

Bohemian
Bohemian

Reputation: 425033

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

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.

Upvotes: 7

ihsan kocak
ihsan kocak

Reputation: 1581

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

Upvotes: -1

Related Questions