Spike Flail
Spike Flail

Reputation: 683

How to compare and reorder an ArrayList of objects based on a list of another objects?

I have 2 arraylists, one of type String and the other is a custom class Person.

List names = new ArrayList<String>(); 
List people = new ArrayList<Person>();

Both lists are populated like so:

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

Notice that the same names have been used in both lists, but added in different order. How can I sort the people arraylist in the same order as the names?

Upvotes: 1

Views: 154

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234847

Since the names array can apparently be in an arbitrary order, the concept of "sorting" isn't very applicable. The most direct approach, I think, is to rebuild the people array from the given names array by using a map. Something like this might work:

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

This assumes that there is a one-to-one correspondence between the elements of names and people based on the name. If that's not a correct assumption, then this approach would have to be modified accordingly.

Upvotes: 2

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

Strange requirement, but you can do it by using a 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);

Upvotes: 3

tj-recess
tj-recess

Reputation: 1809

Use a comparator for sorting people which uses ordering of names list. (Untested code below)

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

Upvotes: 0

Related Questions