Skip to content

Sort ArrayList of custom Objects by property

To sort an ArrayList of custom objects by a property, you can use the Collections.sort method and pass it a custom Comparator.

First, define the Person class with a getAge method:

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

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

  public int getAge() {
    return age;
  }
}

Here's an example of how you can do this:


java
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

Collections.sort(people, new Comparator<Person>() {
  @Override
  public int compare(Person p1, Person p2) {
    return Integer.compare(p1.getAge(), p2.getAge());
  }
});

In this example, the Person class has a getAge method that returns the age of the person. The Comparator compares the ages of two Person objects and returns a negative number if the first person is younger, a positive number if the first person is older, and 0 if the ages are the same.

This will sort the people list in ascending order by age. To sort the list in descending order, you can reverse the comparison by swapping the order of the operands:


java
Collections.sort(people, new Comparator<Person>() {
  @Override
  public int compare(Person p1, Person p2) {
    return Integer.compare(p2.getAge(), p1.getAge());
  }
});

Alternatively, you can use the sort method of the List interface and pass it a Comparator as an argument:


java
people.sort(new Comparator<Person>() {
  @Override
  public int compare(Person p1, Person p2) {
    return Integer.compare(p1.getAge(), p2.getAge());
  }
});

This will sort the people list in ascending order by age. Note that List.sort() delegates to Collections.sort() under the hood.

Note that the sort method uses a modified merge sort algorithm, which has a time complexity of O(n * log(n)). This means that it is efficient for sorting large lists.

For Java 8+, you can use lambda expressions and method references for a more concise approach:

java
people.sort(Comparator.comparingInt(Person::getAge));

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.