Sort ArrayList of custom Objects by property
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
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.
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.
To sort an ArrayList of Person objects using this method:
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
By Age
Using these comparators:
Enhancements with Java 8
Using Lambda Expressions
Java 8 introduced lambda expressions which simplify the implementation of single method interfaces like Comparator.
Using Method References
Method references further simplify the syntax:
Key Points Summary
| Property | Interface | Java Version | Usage Example |
| Age | Comparable | Java 1.2 | Collections.sort(people); |
| Name, Age | Comparator | Java 1.2 | Collections.sort(people, byName); |
| Name (Lambda) | Comparator | Java 8 | people.sort((p1, p2) -> p1.getName().compareTo(p2.getName())); |
| Age (Method Reference) | Comparator | Java 8 | people.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.
Related reading

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.