This post will discuss how to sort a list of objects by multiple attributes in Java.

1. Using Comparator

You can implement a custom Comparator to sort a list by multiple attributes. A Comparator can be passed to Collections.sort() or List.sort() method to allow control over the sort order. i.e., it defines how two items in the list should be compared.

For example, the following code creates a list of Student and in-place sorts it based on the name. If two objects have the same name, their ordering is decided by age. You can pass a method reference to the Comparator.comparing(), and it will extract and returns a comparator based on that function. To sort on multiple attributes, use Comparator.thenComparing() to combine two comparisons.

Download  Run Code

Output:

Student{name=’Akon’, age=15}
Student{name=’John’, age=20}
Student{name=’John’, age=25}
Student{name=’Tony’, age=10}

 
If you prefer the Guava library, you can construct a Comparator using ComparisonChain to perform a chained comparison to facilitate sorting on multiple attributes, as shown below:

Download Code

Output:

Student{name=’Akon’, age=15}
Student{name=’John’, age=20}
Student{name=’John’, age=25}
Student{name=’Tony’, age=10}

 
Similar to Guava’s ComparisonChain, you may use the CompareToBuilder class of the Apache Commons Lang library.

Download Code

Output:

Student{name=’Akon’, age=15}
Student{name=’John’, age=20}
Student{name=’John’, age=25}
Student{name=’Tony’, age=10}

2. Implement Comparable Interface

If an object implements the Comparable interface, you can sort a list of that object using Collections.sort() or List.sort() method. This class’s implementer needs to override the abstract method compareTo(), which compares the object with the specified object. The value returned by the compareTo() decides the position of the object relative to the specified object.

For example, the following code creates a list of Student objects, where Student implements the Comparable interface and the compareTo() method orders elements by name and then by age.

Download  Run Code

Output:

Student{name=’Akon’, age=15}
Student{name=’John’, age=20}
Student{name=’John’, age=25}
Student{name=’Tony’, age=10}

3. Using Stream API

If you need a new sorted list, without modifying the original list, the best option is to use Java 8 Stream API. The idea is to get a stream consisting of the elements of the list, sort it with the sorted() method using comparing comparator, and finally collect all sorted elements in a list.

Download  Run Code

Output:

Student{name=’Akon’, age=15}
Student{name=’John’, age=20}
Student{name=’John’, age=25}
Student{name=’Tony’, age=10}

That’s all about sorting a list of objects by multiple attributes in Java.