Reputation: 1019
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
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
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
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