如何根据另一个对象列表比较和重新排序对象的ArrayList?

时间:2015-05-18 16:02:19

标签: java arraylist

我有2个arraylists,一个是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 arraylist进行排序?

3 个答案:

答案 0 :(得分:3)

奇怪的要求,但您可以使用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);

答案 1 :(得分:2)

由于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));
    }
}

这假设namespeople的元素之间基于名称一一对应。如果这不是一个正确的假设,那么必须相应地修改这种方法。

答案 2 :(得分:0)

使用比较器对使用名称列表排序的人进行排序。 (下面未经测试的代码)

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);
  }
});