如何从列表中检索所有最大值? [英] How can I retrieve all of the maximum values from a list?

查看:64
本文介绍了如何从列表中检索所有最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Employee 的类,该类实现了 Comparable 接口.

I have a class called Employee that implements the Comparable interface.

现在,我的列表中有5个 Employee 对象,每个对象都有其自己的 salary 属性.我想找到所有具有最高工资的 Employee 对象.

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.

我可以使用一个对象

 Employee employee = Collections.max(employeeList);

但是,当我尝试检索具有相同最大值的所有对象的数组或列表时,它仅返回单个 Employee .我该怎么办?

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

此解决方案为O(n),并且需要遍历列表.

This solution is O(n), and requires a single pass through the list.

这篇关于如何从列表中检索所有最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆