How can I retrieve all of the maximum values from a list?
collections, comparable, java, list, max
Solution
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.
Problem
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?