2016-03-28 77 views
0

請大家幫忙!從ArrayList中獲取最大值的數量Java

我有一類這樣的:

public class Person { 
    private int age 
} 

假設我有Person類型的ArrayList,我想通過降的年齡以取出15人,最大年齡排序。我可以對列表進行排序,然後取出值,但如果列表中有大約一千個對象,則需要太多時間。我能更快地做到這一點?

謝謝。 對不起,我的英語!

+0

你可以做**部分**冒泡排序。 –

+0

這當然取決於你在做什麼,但是你確定這是需要花費太多時間的嗎?使用Java8提供的普通「排序」功能對我非新電腦上的ArrayList中的一百萬個對象進行排序大約需要8ms,而千次則不易測量。 –

+0

[如何從List/ArrayList獲取最大值]的可能重複(http://stackoverflow.com/questions/8304767/how-to-get-maximum-value-from-the-list-arraylist) –

回答

0

嘗試:

  1. 覆蓋hashcode()方法更有效率(你應該 覆蓋equals()以及)
  2. 使用TreeSet而不是ArrayList - 它使排序的對象。
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); 
} 
0

您可以嘗試測量。

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

PriorityQueue是這種需求的不錯選擇。要了解關於PriorityQueue的更多信息,請點擊以下鏈接: How do I use a PriorityQueue?

有一點需要注意的是,PriorityQueue迭代器不會按順序提供元素。您必須移除元素才能依次遍歷其元素。

此外,您還需要使用collections.reverseOrder使用PriorityQueue的反向自然順序。要了解更多關於扭轉自然順序的優先順序,請按照下面的鏈接: Reverse natural order using collections.reverseOrder()

0

按升序或降序對數組進行排序,並根據順序選擇數組中的第一個或最後一個項目!

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

更可以發現here