我有一个名为 Employee
的类,它实现了 Comparable
接口(interface)。
现在我的列表中有 5 个 Employee
对象,每个对象都有自己的 salary
属性。我想找到所有具有最高薪水的 Employee
对象。
我可以使用单个对象
Employee employee = Collections.max(employeeList);
但这只会返回一个 Employee
,而我正在尝试检索具有相同最大值的所有对象的数组或列表。我该怎么做?
最佳答案
为了提高效率,您应该遍历列表并自己找到所有最大元素:
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);
}
}
此解决方案的复杂度为 O(n),并且需要单次遍历列表。
关于java - 如何从列表中检索所有最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299087/