2012-04-25 31 views
1

的列表的順序這是我有:排序對象的列表與對象ID

class Person { 
    Integer id; 
    String name; 
} 

// A list of persons: 
List<Person> persons 

// Now I have something like this: 
List<Integer> ids // where the ids are stored in an specific order 

基本上我以相同的順序,如IDS想排序的人員名單。

有沒有更好的方法,然後像兩個循環一樣使用並創建一個新的Person-List?

問候& & TIA

noircc

回答

3

使用Collections.sort使用定製Comparator如下所示。比較得到比較的人的ID,並在它們出現在IDS列表,它爲了工作了:

List<Person> persons = ...; 
final List<Integer> ids = ...; 

Collections.sort(persons, new Comparator<Person>() { 
    @Override 
    public int compare(Person p1, Person p2) { 
     int index1 = ids.indexOf(p1.getId()); 
     int index2 = ids.indexOf(p2.getId()); 
     return index1 < index2 ? -1 : (index1 == index2 ? 0 : 1); 
    } 
}); 

注:此代碼假定列表中的所有的人的ID將出現在IDS列表。

+0

複雜性是什麼? – 2012-04-25 16:13:26

+0

Collections.sort是O(nlogn),但是對於每個比較都有兩個O(n)索引查找,所以不能非常有效,但至少沒有創建臨時收藏。 – dogbane 2012-04-25 16:36:31

+0

恩,謝謝! – noircc 2012-04-26 07:43:20

-1
  1. 地圖每個ids納入其指數:Map<Integer, Integer> idToIndex;
  2. 運行以下循環。

for (int i = 0, size = persons.length - 1; i < size; ++i) { 
    var targetIndex = idToIndex.get(persons.get(i).id); 
    if (targetIndex != i) { 
    persons[i] <-> persons[targetIndex]; 
    } 
} 
+0

看起來像javascript – noircc 2012-04-25 16:06:09

+0

...和C++,也是:)'<->'意思是「交換」,猜測這很直觀。 – 2012-04-25 16:13:55

+0

-1這不會起作用,因爲您正在交換人員,最終可能會跳過已交換的人員。例如嘗試你的算法與人= [2,5,1,3]和ids = [1,3,5,2]。它錯誤地給出了3,1,5,2,因爲它與2交換了3。 – dogbane 2012-04-25 16:33:24