【问题标题】:get number of max values from ArrayList Java从 ArrayList Java 中获取最大值的数量
【发布时间】:2016-03-28 04:32:00
【问题描述】:

请帮忙!

我有这样的课:

public class Person {
    private int age
}

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

谢谢。 对不起我的英语!

【问题讨论】:

  • 您可以进行部分冒泡排序。
  • 这当然取决于你在做什么,但你确定这是需要太多时间的那种吗?在我不是很新的计算机上使用 Java8 提供的普通 sort 对 ArrayList 中的一百万个对象进行排序大约需要 8 毫秒,一千甚至都不容易测量。

标签: java arraylist


【解决方案1】:

尝试:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您可以尝试测量。

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

      【讨论】:

        【解决方案4】:

        PriorityQueue 是此类需求的不错选择。要了解有关 PriorityQueue 的更多信息,请点击以下链接: How do I use a PriorityQueue?

        需要注意的一点是 PriorityQueue 迭代器没有按顺序提供元素。您必须删除元素才能按顺序迭代其元素。

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

        【讨论】:

          【解决方案5】:

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

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

          更多信息请关注here

          【讨论】:

            猜你喜欢
            • 2015-07-05
            • 2014-12-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-28
            • 2012-11-05
            • 2014-01-27
            • 1970-01-01
            相关资源
            最近更新 更多