1

这就是我所拥有的:

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

基本上我想按照与ID相同的顺序对人员列表进行排序。

有没有更好的方法然后使用两个循环并创建一个新的人员列表?

问候 && 蒂亚

noircc

4

2 回答 2

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 列表中。

于 2012-04-25T16:05:58.043 回答
-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];
  }
}
于 2012-04-25T15:53:22.413 回答