ArrayList
Custom Objects
Property Sorting
Java Programming
Data Structures

Sort ArrayList of custom Objects by property

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Sorting an ArrayList of custom objects by a specific property in Java is a common task that can be achieved using several approaches. This process is crucial in many applications where data needs to be organized according to specific criteria for effective processing or display. Java provides robust tools and APIs to customize sorting behavior, such as Comparable and Comparator interfaces.

Understanding the Basics

Custom Object Definition

Consider a class Person with properties name and age. We need to sort a list of Person objects based on these properties.

java
1public class Person {
2    private String name;
3    private int age;
4
5    // Constructor
6    public Person(String name, int age) {
7        this.name = name;
8        this.age = age;
9    }
10
11    // Getters and Setters
12    public String getName() {
13        return name;
14    }
15
16    public int getAge() {
17        return age;
18    }
19
20    // toString method for easy printing
21    @override
22    public String toString() {
23        return "Person{name='" + name + "', age=" + age + "}";
24    }
25}

Sorting Using Comparable

Implementing the Comparable interface allows a class to define a natural ordering of its objects. The class must implement the compareTo method.

java
1public class Person implements Comparable<Person> {
2    // fields, constructors, and methods as above
3
4    @Override
5    public int compareTo(Person other) {
6        return this.age - other.age; // Ascending order by age
7    }
8}

To sort an ArrayList of Person objects using this method:

java
1ArrayList<Person> people = new ArrayList<>();
2people.add(new Person("Alice", 22));
3people.add(new Person("Bob", 20));
4
5Collections.sort(people);

Sorting Using Comparator

You can also define multiple separate sorting orders using the Comparator interface. This allows sorting on different properties without modifying the object's class.

By Name

java
1Comparator<Person> byName = new Comparator<Person>() {
2    @Override
3    public int compare(Person p1, Person p2) {
4        return p1.getName().compareTo(p2.getName());
5    }
6};

By Age

java
1Comparator<Person> byAge = new Comparator<Person>() {
2    @Override
3    public int compare(Person p1, Person p2) {
4        return Integer.compare(p1.getAge(), p2.getAge());
5    }
6};

Using these comparators:

java
Collections.sort(people, byName); // Sort by name
Collections.sort(people, byAge);  // Sort by age

Enhancements with Java 8

Using Lambda Expressions

Java 8 introduced lambda expressions which simplify the implementation of single method interfaces like Comparator.

java
// Sorting by name using lambda
people.sort((Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));

Using Method References

Method references further simplify the syntax:

java
// Sorting by age using method reference
people.sort(Comparator.comparingInt(Person::getAge));

Key Points Summary

PropertyInterfaceJava VersionUsage Example
AgeComparableJava 1.2Collections.sort(people);
Name, AgeComparatorJava 1.2Collections.sort(people, byName);
Name (Lambda)ComparatorJava 8people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));
Age (Method Reference)ComparatorJava 8people.sort(Comparator.comparingInt(Person::getAge));

Conclusion

Choosing between Comparable and Comparator depends largely on the context and requirements of your application. If sorting needs to be done on several different attributes of an object, using Comparator provides greater flexibility. In contrast, Comparable is suitable when there is a single natural sorting order. Java 8 enhancements such as lambda expressions and method references make the implementation concise and more readable.


Course illustration
Course illustration

All Rights Reserved.