[英]get number of max values from ArrayList Java
請幫忙!
我有這樣的課:
public class Person {
private int age
}
假設我有一個Person類型的ArrayList,我想按年齡的降序取出最大年齡的15個人。 我可以對列表進行排序,然后取出值,但是如果列表中包含大約一千個對象,則將花費太多時間。 我可以更快地做到這一點?
謝謝。 對不起,我的英語!
嘗試:
hashcode()
方法以提高效率(還應該覆蓋equals()
) 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.