我有两个数组,一个类型为String,另一个是自定义类Person。
List names = new ArrayList<String>();
List people = new ArrayList<Person>();这两个列表都是这样填充的:
names.add("bob");
names.add("joe");
names.add("tom");
people.add(new Person("joe")); //Assuming Person has a name property
people.add(new Person("tom"));
people.add(new Person("bob"));请注意,在两个列表中都使用了相同的名称,但按不同的顺序添加。如何按照与people相同的顺序对names数组进行排序
发布于 2015-05-18 16:10:46
奇怪的需求,但您可以通过使用Map来完成
Map<String, Person> personMap = new HashMap<>();
//Assuming people is declared rightfully as List<Person> rather than just List
for (Person people : people) {
personMap.put(person.getName(), person);
}
List<Person> results = new ArrayList<>();
for (String name : names) {
if (personMap.containsKey(name)) {
results.add(personMap.get(name));
}
}
//in case you need to work with people only
people.clear();
people.addAll(results);发布于 2015-05-18 16:11:31
由于names数组显然可以按任意顺序排列,所以“排序”的概念并不适用。我认为,最直接的方法是使用映射从给定的people数组重新构建names数组。像这样的东西可能会起作用:
void reoderPeople(ArrayList<Person> people, ArrayList<String> names) {
// first build the map
Map<String, Person> map = new HashMap<>();
for (Person p : people) {
map.add(p.getName(), p);
}
// now re-create the people array
people.clear();
for (String name : names) {
people.add(map.get(name));
}
}这假设基于名称在names和people元素之间存在一对一的对应关系。如果这不是一个正确的假设,那么这个方法就必须进行相应的修改。
发布于 2015-05-18 16:09:35
使用比较器对人进行排序,使用名称列表的排序。(下面是未经测试的代码)
Collections.sort(people, new Comparator<Person>(){
public int comapre(Person a, Person b) {
Integer indexA = names.indexOf(a.getName());
Integer indexB = names.indexOf(b.getName());
return indexA.compareTo(indexB);
}
});https://stackoverflow.com/questions/30307918
复制相似问题