Write a Java Program to Sort ArrayList of Custom Objects By Property

Sorting an ArrayList of custom objects is a common requirement in Java programming.

In this tutorial, we will cover how to sort an ArrayList of custom objects by a specific property using Java’s built-in Comparator interface.


Before we dive into the code, let’s first define what an ArrayList is.

An ArrayList is a resizable array that stores objects.

It provides us with dynamic arrays in Java.

The elements of an ArrayList are not limited to a specific data type and can store any object.

Now let’s say we have a custom object called “Person” with the properties “name” and “age”.

We want to sort an ArrayList of Person objects by age.

Here is the code to achieve that:

javaCopy codeimport java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<>();
        people.add(new Person("John", 30));
        people.add(new Person("Jane", 25));
        people.add(new Person("Bob", 40));

        // Sorting by age using Comparator
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.getAge() - p2.getAge();
            }
        });

        // Printing the sorted list
        for (Person person : people) {
            System.out.println(person.getName() + " " + person.getAge());
        }
    }
}

In the above code, we create an ArrayList of Person objects and add some instances to it.

Then, we use the Collections.sort() method to sort the ArrayList by age using a Comparator.

A Comparator is an interface that allows us to define a custom comparison method for objects.

In the code above, we create an anonymous inner class that implements the Comparator interface and defines the compare() method.

The compare() method compares the ages of two Person objects and returns an integer value based on their age difference.

Finally, we print the sorted ArrayList using a for-each loop.


In conclusion, sorting an ArrayList of custom objects by a specific property can be achieved using Java’s built-in Comparator interface.

By defining a custom comparison method, we can sort the ArrayList based on the desired property.