从ArrayList Java获取最大值的数量

时间:2016-03-28 04:32:01

标签: java arraylist

请帮忙!

我有一个这样的课程:

public class Person {
    private int age
}

假设我有一个Person类型的ArrayList,我想按年龄的降序取出15个最大年龄排序的人。我可以对列表进行排序,然后取出值,但如果列表中有大约一千个对象,则需要花费太多时间。我能以哪种方式更快地完成这项工作?

谢谢。 抱歉我的英文!

5 个答案:

答案 0 :(得分:0)

尝试:

  1. 覆盖hashcode()方法以提高效率(您应该这样做 同时覆盖equals()
  2. 使用TreeSet代替ArrayList - 它会保持对象的排序。

答案 1 :(得分:0)

如果您不需要重新排序列表,只需循环浏览每个项目 我创建了一个带有数组的示例解决方案,您可以将其应用到列表中,只需重新编写比较器

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

答案 2 :(得分:0)

您可以尝试衡量。

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

答案 3 :(得分:0)

PriorityQueue是这种要求的不错选择。要了解有关PriorityQueue的更多信息,请访问以下链接: How do I use a PriorityQueue?

需要注意的一点是,PriorityQueue迭代器不按顺序提供元素。你必须删除元素以按顺序迭代它的元素。

您还需要使用collections.reverseOrder使用PriorityQueue的反向自然顺序。要了解有关撤消自然顺序PriorityQueue的更多信息,请访问以下链接: Reverse natural order using collections.reverseOrder()

答案 4 :(得分:0)

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

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

可以找到更多 here