Learn to use Collections.sort() method to sort a list of objects using some examples.
By default, the
sort()
method sorts a given list into ascending order (or natural order). We can use Collections.reverseOrder() method, which returns a Comparator, for reverse sorting.
1. Sorting in Natural Order and Reverse Order
Collections.sort(list); //Sorts in natural order
Collections.sort(list, Collections.reverseOrder()); //Sorts in reverse order
- Above method sorts the specified
list
of items into their natural order. - All items must implement the Comparable interface.
- All items must be mutually comparable and should not throw
ClassCastException
. - This sort is guaranteed to be stable. It means that equal elements will not be reordered as a result of the sort.
- The specified
list
must be modifiable, but need not to be resizable. - The
sort()
does not return any value.
1.1. Sorting an ArrayList of Strings
Java program to sort a list of strings lexicographically (in the dictionary order).
List<String> names =
Arrays.asList("Alex", "Charles", "Brian", "David");
//Prints - [Alex, Brian, Charles, David]
Collections.sort(names);
//Prints - [David, Charles, Brian, Alex]
Collections.sort(names, Collections.reverseOrder());
1.2. Sorting ArrayList of Objects by Field
We may require to sort a list of custom objects which can have their own sorting logic. In this case, implement the Comparator
interface in the custom class.
For example, the domain object Employee
has default sorting on the name
field. Checkout for comparison logic in compareTo() method.
public class Employee implements Comparable<Employee>{
private Integer id;
private String name;
private String email;
private LocalDate dateOfBirth;
//Getters and Setters
@Override
public int compareTo(Employee e) {
return this.getName().compareTo(e.getName());
}
}
Nest Java program sorts the list of Employee objects by their name;
ArrayList<Employee> employees = methodReturnsUnsortedList();
//Narutal order sorting
Collections.sort(employees);
//Reverse sorting
Collections.sort(employees, Collections.reverseOrder());
2. Custom Sorting using Comparators
The second parameter in sort()
method takes an instance of Comparator
.
We can implement any kind of comparison logic with the help of comparators and then we can use sort()
method to sort the list based on the given custom logic.
Collections.sort(List, Comparator);
We can create a separate Comparator
instances for each kind of sorting need, and then we can combine those instances to create group sorting effect.
For example, if we want to sort the Employee list on three fields – id, name, and age. In this case, we need to create 3 Comparator
instances.
2.1. Creating Custom Comparator
This is general syntax to create a Comparator in Java. In this case, we are creating a Comparator
which will sort the Employee list by id
field.
Comparator<Employee> compareById = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.getId().compareTo(o2.getId());
}
};
Comparator<Employee> compareByName = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
};
We can use lambda expression for further shortening the syntax.
//Id Comparator
Comparator<Employee> compareById = (Employee o1, Employee o2) ->
o1.getId().compareTo( o2.getId() );
//Name Comparator
Comparator<Employee> compareByName = (Employee o1, Employee o2) ->
o1.getName().compareTo( o2.getName() );
2.2. Using Comparator for Sorting
ArrayList<Employee> employees = getUnsortedEmployeeList();
Comparator<Employee> compareById =
(Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() );
Collections.sort(employees, compareById);
Collections.sort(employees, compareById.reversed());
3. Conclusion
In the above code examples, we learned to sort an ArrayList in default order or reverse order.
We also learned to use the Comparators for implementing the custom sorting logic.
Happy Learning !!