How do you sort an ArrayList?

Given the following ArrayList
1
2
3
4
List<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("blue");



You can simply use the built-in Collections.sort method to sort your ArrayList.

Default ArrayList Sort
1
2
3
4
List<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("blue");



The ArrayList now contains the following elements in order

ArrayList Contents
blue
green
red



Okay, that’s great, but what if you want to sort a custom object for example a person object with an age attribute.

Let’s first define a custom Person Object

Person.java
1
2
3
4
5
6
7
8
9
public class Person {
    public String name;
    public int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}



Next let’s populate the List

Populate ArrayList with People
1
2
3
4
List<Person> people = new ArrayList<Person>();
people.add(new Person("Joe", 28));
people.add(new Person("Jane", 26));
people.add(new Person("Jeff", 53));



At this point we can again use the Collections.sort method but this time we need to provide a custom Comparator because the sort doesn’t know how to determine the order of your objects. We can create a Comparator that compares by age.

AgeComparator.java
1
2
3
4
5
6
public class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age - b.age;
    }
}



Now all we need to do is use Collections.sort with a new AgeComparator

Sort with Comparator
1
Collections.sort(people, new AgeComparator());



The ArrayList now contains the following elements in order

ArrayList Contents
Jane=26
Joe=28
Jeff=53