请帮帮我!我有这样一节课:
public class Person { private int age }
假设我有一个person类型的arraylist,我想按年龄的降序对15个最大年龄的人进行排序。我可以对列表进行排序,然后取出值,但如果列表中有大约1000个对象,则会花费太多时间。哪种方法我能做得更快?谢谢您。对不起我的英语!
fruv7luv1#
尝试:覆盖 hashcode() 方法更有效(您应该重写 equals() 以及)使用 TreeSet 而不是 ArrayList -它使对象保持排序。
hashcode()
equals()
TreeSet
ArrayList
xpcnnkqh2#
如果你不需要重新排序你的列表,只要通过每一个项目循环我创建了一个带有数组的示例解决方案,你可以应用到你的列表,只要重新编写你的比较器
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); }
sy5wg1nm3#
你可以试着测量一下。
public List<Person> findMaxAge15(List<Person> persons) { return persons.sorted(Comparator.comparing(Person::getAge).reversed()) .limit(15) .collect(Collectors.toList()); }
edqdpe6u4#
对于这种需求,priorityqueue是很好的选择。要了解有关priorityqueue的更多信息,请访问以下链接:如何使用priorityqueue?需要注意的一点是priorityqueue迭代器没有按顺序提供元素。您必须删除元素才能按顺序遍历其元素。您还需要使用collections.reverseorder使用priorityqueue的反向自然顺序。要了解有关反转自然顺序优先级队列的更多信息,请访问以下链接:使用collections.reverseorder()反转自然顺序
ljo96ir55#
按升序或降序对数组排序,并根据顺序选择数组中的第一项或最后一项!
Collections.sort(arrayList); // Sort the arraylist arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
更多信息可以在这里找到。
5条答案
按热度按时间fruv7luv1#
尝试:
覆盖
hashcode()
方法更有效(您应该重写equals()
以及)使用
TreeSet
而不是ArrayList
-它使对象保持排序。xpcnnkqh2#
如果你不需要重新排序你的列表,只要通过每一个项目循环我创建了一个带有数组的示例解决方案,你可以应用到你的列表,只要重新编写你的比较器
sy5wg1nm3#
你可以试着测量一下。
edqdpe6u4#
对于这种需求,priorityqueue是很好的选择。要了解有关priorityqueue的更多信息,请访问以下链接:如何使用priorityqueue?
需要注意的一点是priorityqueue迭代器没有按顺序提供元素。您必须删除元素才能按顺序遍历其元素。
您还需要使用collections.reverseorder使用priorityqueue的反向自然顺序。要了解有关反转自然顺序优先级队列的更多信息,请访问以下链接:使用collections.reverseorder()反转自然顺序
ljo96ir55#
按升序或降序对数组排序,并根据顺序选择数组中的第一项或最后一项!
更多信息可以在这里找到。