使用对象ID列表的顺序对对象列表进行排序

时间:2012-04-25 15:45:36

标签: java list sorting

这就是我所拥有的:

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?

问候&amp;&amp; TIA

noircc

2 个答案:

答案 0 :(得分:3)

使用自定义Collections.sort使用Comparator,如下所示。比较器获取被比较人员的ID,并按照他们出现在ID列表中的顺序计算出来:

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将显示在ID列表中。

答案 1 :(得分:-1)

  1. 将每个ids映射到其索引:Map<Integer, Integer> idToIndex;
  2. 运行以下循环。

  3. 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];
      }
    }