【问题标题】:How to compare and reorder an ArrayList of objects based on a list of another objects?如何根据另一个对象的列表比较和重新排序对象的 ArrayList?
【发布时间】:2015-05-18 16:02:18
【问题描述】:

我有 2 个数组列表,一个是 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"));

请注意,两个列表中使用了相同的名称,但添加的顺序不同。如何以与names 相同的顺序对people 数组列表进行排序?

【问题讨论】:

  • mkyong.com/java/… 可能是一本好书。您需要一个 Comparator 或使 Person Comparable。
  • names 是否保证按字母顺序排列?
  • 您需要按广告顺序还是按字母顺序?
  • 您的意思是“排序”还是“重新排序”?如“重新排列people 数组以匹配names”数组中的顺序?
  • names 不保证按字母顺序排列。

标签: java arraylist


【解决方案1】:

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

【讨论】:

  • 有什么理由使用单独的results 列表?为什么不简单地清除 people 并在迭代 names 时直接添加?
  • @TedHopp 好吧,我正在考虑使用这里提出的 Java 8 解决方案 in this other answer I posted 并使用这种方式。
【解决方案2】:

由于names 数组显然可以是任意顺序,因此“排序”的概念不太适用。我认为最直接的方法是使用映射从给定的names 数组重建people 数组。这样的事情可能会奏效:

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的元素基于名称是一一对应的。如果这不是一个正确的假设,则必须相应地修改此方法。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 最后,一种可行的基于比较的方法(假设将public int comapre 更改为public int compare)。但与构建地图相比,这似乎效率非常低。
    猜你喜欢
    • 2023-04-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2019-07-09
    相关资源
    最近更新 更多