2012-04-25 58 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