从ArrayList Java中获取最大值的数目



请帮忙!

我有一门课是这样的:

public class Person {
    private int age
}

假设我有一个Person类型的ArrayList,我想按年龄的降序取出15个最大年龄排序的Person。我可以对列表进行排序,然后取出值,但如果列表中有大约一千个对象,则会花费太多时间。我用哪种方法做得更快?

谢谢。对不起我的英语!

尝试:

  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迭代器没有按顺序提供元素。您必须删除元素才能按顺序迭代其元素。

此外,您还需要使用collections.reverseOrder使用PriorityQueue的反向自然顺序。要了解有关反转自然顺序PriorityQueue的更多信息,请访问以下链接:使用集合反转自然顺序。reverseOrder()

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

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

更多信息可在此处找到

最新更新