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.
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.

