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
?
3 Answers 3
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);
2 Comments
results
list? Why not simply clear people
and add directly to that when iterating through names
?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.
Comments
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);
}
});
1 Comment
public int comapre
to public int compare
). But this seems like a strikingly inefficient compared to building a map.
names
guaranteed to be alphabetical?people
array to match the order in thenames
" array?names
is not guaranteed alphabetical.