Learn to use Collections.sort() method to sort arraylist of custom objects in java with examples. By default, this method sorts the unsorted list into ascending order, according to the natural ordering of its elements. We can use Collections.reverseOrder() method for reverse sorting.
1. Sort ArrayList of objects – Collections.sort( list )
- It sorts the specified
list
into ascending order or their natural order. - All elements in the
list
must implement the Comparable interface. - All elements in the list 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 be resizable. - Method does not return any value.
1.1. Sort arraylist of strings
List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David"); //Natural order Collections.sort(names); //[Alex, Brian, Charles, David] //Reverse order Collections.sort(names, Collections.reverseOrder()); [David, Charles, Brian, Alex]
1.2. Sort arraylist of custom objects by field with Comparable
We may need to sort list of user defined objects which have their own sorting logic. In that case, implement the Comparator
interface in those domain class and use same approach as above.
The domain object Employee
is as below. Checkout for comparison logic in compareTo() method.
public class Employee implements Comparable< Employee >{ private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "Employee [id=" + id + "]"; } @Override public int compareTo(Employee o) { return this.getId().compareTo(o.getId()); } }
Java program to sort list of employee objects by id, in ascending and descending orders.
import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class JavaSort { public static void main(String[] args) { ArrayList<Employee> employees = getUnsortedEmployeeList(); //1. Employee ids in ascending order Collections.sort(employees); System.out.println(employees); //2. Employee ids in reverse order Collections.sort(employees, Collections.reverseOrder()); System.out.println(employees); } //Returns an unordered list of employees private static ArrayList<Employee> getUnsortedEmployeeList() { ArrayList<Employee> list = new ArrayList<>(); Random rand = new Random(10); for(int i = 0; i < 5; i++) { Employee e = new Employee(); e.setId(rand.nextInt(100)); list.add(e); } return list; } }
Program output.
[E [id=13], E [id=46], E [id=80], E [id=90], E [id=93]] [E [id=93], E [id=90], E [id=80], E [id=46], E [id=13]]
2. Sort ArryList of objects – Collections.sort( list, Comparator )
If domain object does not implement Comparable
interface, then we can use custom Comparator
implementations. Use lambda expression to even more shorten the syntax.
2.1. Create Custom Comparators
This is general syntax to create a comparator in Java.
Comparator<Employee> compareById = new Comparator<Employee>() { @Override public int compare(Employee o1, Employee o2) { return o1.getId().compareTo(o2.getId()); } };
If in Java 8, use lambda expression to make the syntax more readable.
Comparator<Employee> compareById = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() ); //use any other field //First name sorter Comparator<Employee> compareByFirstName = (Employee o1, Employee o2) -> o1.getFirstName().compareTo( o2.getFirstName() ); //Last name sorter Comparator<Employee> compareByLastName = (Employee o1, Employee o2) -> o1.getLastName().compareTo( o2.getLastName() );
2.2. Sort list of objects by field with Comparator
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());
Program output.
[E [id=13], E [id=46], E [id=80], E [id=90], E [id=93]] [E [id=93], E [id=90], E [id=80], E [id=46], E [id=13]]
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
References:
Collections.sort()
List.sort()
Ask Questions & Share Feedback