这就是我所拥有的:
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 相同的顺序对人员列表进行排序。
有没有更好的方法然后使用两个循环并创建一个新的人员列表?
问候&&蒂亚
黑色
最佳答案
使用自定义Comparator
来使用Collections.sort
,如下所示。比较器获取被比较人员的 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 都会出现在 ids 列表中。
关于java - 使用对象 ID 列表的顺序对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10319088/