Java Program to Sort ArrayList of Custom Objects by Property

Java Program to Sort ArrayList of Custom Objects by Property

Sorting an ArrayList of Custom objects by property is a common thing in Java programming when you deal with a large set of data. Sometimes, you may want to sort an ArrayList based on one or more properties of the objects. Java simply offers many ways to achieve this, which you will be learning in this blog. Let’s start learning with the basics.

Table of Contents:

What is an ArrayList in Java?

Java ArrayList is a part of the collections framework, and it is a class in java.util package. It provides us with the dynamic-sized arrays in Java.

An ArrayList is a dynamic array that can hold a collection of objects. Java provides several ways to achieve this; the most common is by using the Comparator interface or lambda expressions.

Syntax of creating an empty ArrayList:

ArrayList<E> list = new ArrayList<>();

How to Sort an ArrayList of Custom Objects by Property in Java?

There are mainly two different approaches to sorting an ArrayList of custom objects. These are:

  • Using Comparator Interface
  • Using Comparable Interface

Let us understand both of these in detail.

Method 1: Sort ArrayList Using Java Comparator

The Comparator interface is used when you need to define the custom sorting logic that is separate from that of the object’s class. It is flexible because you can create different comparators for different sorting criteria (e.g., by age, by name, etc.) and pass them to the sorting getter methods.

Example:

Java

Output:

Using the Comparator Interface getter method

Explanation: In the above code, the Comparator interface is used to sort the Person objects by age. A Comparator is passed to Collections.sort() with a compare method that compares the ages. This allows sorting of the ArrayList based on the age.

Method 2: Sort ArrayList Using Comparable Interface in Java

The Comparable interface is used when the natural ordering of the object is defined in the class itself. This means that you can implement the compareTo method inside the object’s class, and it defines how the objects of that class should be sorted by default.

Example:

Java

Output:

Using the Comparable Interface getter method

Explanation: In the above code, the Person class implements the Comparable interface to compare the objects by age. The compareTo method sorts the Person objects using Collections.sort(people).

Sorting Java ArrayList Alphabetically by String Property

When you have a list of custom objects and you want to sort ArrayList using Comparator alphabetically based on a string field (like a name), you can use the Comparator interface in Java.

For example, to sort a Java ArrayList by the name property. Below is the Person.java file, which has the getters and setters for the String name and int age, and the method toString is used to display the Person object.

Java

In the SortPersonList.java file, the object of the person is made, and then the sorting is performed through the Comparator; further, the output is printed.

Java

Output:

Java sorting in alphabetically using getter method in getter function

Explanation: We are comparing names using the compareToIgnoreCase method to make the sorting case-insensitive. The getName() is a getter method (or getter function) that accesses the name field of each Person object. This is a common way to sort ArrayList of objects in Java when sorting by string properties like names, titles, or locations.

How to Sort ArrayList in Descending Order in Java?

By default, Java sorts in ascending order. But if you want to sort an ArrayList in descending order, you can reverse the sorting logic. If you’re sorting by a numeric property like age. Here’s how to do it using a Comparator:
In the below Java program, the ArrayList of integers is sorted by using the custom Comparator, and then the output is printed in decreasing order.

Java

Output:

java sort to arraylist for custom logic in descending order

Explanation: Java sort list by property is helpful when you want to sort custom objects in Java in reverse order based on a property. Whether sorting by age, salary, or date, descending order is often useful in reports or ranking systems.

Comparator vs Comparable in Java: Key Differences

Following are the differences between Comparator and Comparable Interface in Java:

Feature Comparator Comparable
Purpose Used for custom sorting of objects. Defines the natural ordering of objects.
Location of Sorting Logic External to the class, in a separate class or method. Defined inside the class itself.
Method Used compare(T o1, T o2) compareTo(T o)
Flexibility Very flexible. Multiple comparators can be created. Limited flexibility. Only one natural order is allowed.
Usage Can sort by various properties using different comparators. Sorts are based on a single property (natural ordering).
Modifying the Class Does not require modifying the custom class. Requires modifying the class to implement Comparable.
Multiple Sorting Criteria Can define multiple sorting criteria with different comparators. Can only define one natural sorting order.
Sorting Example Collections.sort(list, new Comparator<>() {...}) Collections.sort(list) or list.sort() (if compareTo is implemented)
Common Usage Sorting by various properties, reverse order, custom logic. Sorting by a default property (e.g., age, name).
Default Sorting No natural order is defined; must define comparison explicitly. Provides natural ordering of objects within the class.

Conclusion

In Java, sorting an ArrayList of custom objects can be done by using both the Comparator and Comparable interfaces. The Comparator allows for the custom sorting defined outside the object class, providing flexibility for different sorting criteria. On the other hand, the Comparable interface defines the natural sorting order within the object class itself. You have also learned Java Comparable vs Comparator. Both methods help in organizing and sorting the data efficiently in Java.

If you want to learn more about Java, you can refer to our Java Course.

Java Program to Sort ArrayList of Custom Objects by Property – FAQs

Q1. How to sort a list of custom objects in Java by property?

You can also sort a list of custom objects using the Collections. sort() method

Q2. How to sort an ArrayList based on a parameter?

An ArrayList can be sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in Ascending Order.

Q3. Should I use Comparable or Comparator for sorting in Java?

The Comparable interface can be used to provide a single way of sorting, whereas the Comparator interface is used to provide different ways of sorting.

Q4. Can an ArrayList be a parameter?

Yes, you can pass an ArrayList of custom objects as a parameter in Java

Q5. What is the fastest way to sort a list?

QuickSort is usually the fastest sorting algorithm. Its performance is measured most of the time in O(N × log N).

Q6. What is the best way to sort ArrayList of objects in Java using Comparator?

You can sort ArrayList of objects in Java by using Collections.sort(list, comparator) or list.sort(comparator) with a custom Comparator.

Q7. Can we use lambda expressions for sorting in Java?

Yes, lambda expressions simplify sorting: list.sort((a, b) -> a.getField().compareTo(b.getField())).

Q8. How to sort Java ArrayList in descending order?

Use Collections.sort(list, Collections.reverseOrder()) or list.sort(Comparator.reverseOrder()).

Q9. Is Collections.sort() stable in Java?

Yes, Collections.sort() is stable and maintains the order of equal elements.

Q10. Can we sort multiple fields in Java objects?

Yes, chain comparators using thenComparing() for multi-field sorting.

Q11. How to avoid NullPointerException while sorting a list?

Use Comparator.nullsFirst() or nullsLast() to handle nulls safely during sorting.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner