繁体   English   中英

从ArrayList Java获取最大值

[英]get number of max values from ArrayList Java

请帮忙!

我有这样的课:

public class Person {
    private int age
}

假设我有一个Person类型的ArrayList,我想按年龄的降序取出最大年龄的15个人。 我可以对列表进行排序,然后取出值,但是如果列表中包含大约一千个对象,则将花费太多时间。 我可以更快地做到这一点?

谢谢。 对不起,我的英语!

尝试:

  1. 覆盖hashcode()方法以提高效率(还应该覆盖equals()
  2. 使用TreeSet而不是ArrayList它使对象保持排序。

如果您不需要重新排序列表,只需循环遍历我创建的带有数组的示例解决方案的每个项目,就可以将其应用于列表,只需重写比较器即可

public static void main(String[] args) {
    int[] a = { 3, 4, 5, 2, 3, 4, 1, 2, 4, 5, 6, 7, 4, 3, 5, 7, 2, 7 };
    int countMax = 0;
    int max = -1;
    for (int i = 0; i < a.length; i++) {
        if (max < a[i]) {
            countMax = 1;
            max = a[i];
        } else if (max == a[i]) {
            countMax++;
        }
    }
    System.out.println(countMax);
}

您可以尝试测量。

public List<Person> findMaxAge15(List<Person> persons) {
    return persons.sorted(Comparator.comparing(Person::getAge).reversed())
        .limit(15)
        .collect(Collectors.toList());
}

对于这种要求,PriorityQueue是一个不错的选择。 要了解有关PriorityQueue的更多信息,请点击以下链接: 如何使用PriorityQueue?

要注意的一件事是PriorityQueue迭代器未按顺序提供元素。 您必须删除元素以按顺序遍历其元素。

另外,您还需要通过collections.reverseOrder使用PriorityQueue的自然逆序。 要了解有关逆转自然顺序PriorityQueue的更多信息,请点击以下链接: 使用collections.reverseOrder()逆向自然顺序

按升序或降序对数组进行排序,然后根据顺序选择数组中的第一项或最后一项!

Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort

这里可以找到更多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM