Object ArrayList Sort
Let’s say we have a simple class called Person
public class Person{
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
If you want to create an ArrayList of Person objects and sort it by name you can do the following:
// populate the ArrayList with some objects
ArrayList<Person> arpList = new ArrayList<TransgressionTab.Person>();
arpList.add(new Person("Onasis", 54));
arpList.add(new Person("Spartakus", 12));
arpList.add(new Person("Oneiro", 1));
arpList.add(new Person("Bomb", 12));
// sort it
Collections.sort(arpList,new Comparator<Person>() {
@Override
public int compare(Person s1,Person s2) {
return s1.name.compareToIgnoreCase(s2.name);
}
});
Comments