ArrayList sort() method sorts the list according to the order induced by the specified Comparator instance. All elements in the list must must be mutually comparable.
1. ArrayList sort() method
The sort() method accepts an instance of Comparator
implementing class which must be able to compare the elements contained in the arraylist.
Internally, the sort()
method uses Arrays.sort()
method to compare and sort the elements in the list.
public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
Method parameter – Comparator implemetation.
Method returns – void
.
Method throws – ConcurrentModificationException
if list is modified while sort()
method is not finished.
2. ArrayList sort() – Sort list of objects by field
Comparators are most useful when we want to sort a given list of objects – but not in natural order. For example, a list of employees should be sorted on their employee id, naturally.
Another usecase of comparator is that when objects in the list are not implementing Comparable interface. Also, we may want to sort objects list in different ways in different scenarios.
For example, an employee list can be sorted by their name, age or their any other such field. Comparator are best fit in these types of requirements.
2.1. Employee Class
Let’s create a simple employee class with only 3 fields to make this example cleaner.
import java.time.LocalDate; public class Employee { private Long id; private String name; private LocalDate dob; public Employee(Long id, String name, LocalDate dob) { super(); this.id = id; this.name = name; this.dob = dob; } //Getters and Setters @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]"; } }
2.2. Comparator classes to enable sorting on different fields
Comparator to sort the employee list by name alphabetically.
import java.util.Comparator; public class NameSorter implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o2.getName().compareToIgnoreCase(o1.getName()); } }
Comparator to sort the employee list by age in ascending order.
import java.util.Comparator; public class AgeSorter implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o2.getDob().compareTo(o1.getDob()); } }
Comparator to sort the employee list by id.
import java.util.Comparator; public class IdSorter implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o2.getId().compareTo(o1.getId()); } }
2.3. ArrayList sort() example
Now let’s use the comparator classes to sort a list of employees by name.
import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<Employee> employees = new ArrayList<>(); employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21))); employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22))); employees.add(new Employee(3l, "David", LocalDate.of(2018, Month.APRIL, 25))); employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23))); employees.add(new Employee(2l, "Edwin", LocalDate.of(2018, Month.APRIL, 24))); employees.sort(new NameSorter()); System.out.println(employees); } }
Program output.
[ Employee [id=1, name=Alex, dob=2018-04-21], Employee [id=4, name=Brian, dob=2018-04-22], Employee [id=3, name=David, dob=2018-04-25], Employee [id=5, name=Charles, dob=2018-04-23], Employee [id=2, name=Edwin, dob=2018-04-24]]
Now let’s use the comparator classes to sort a list of age.
import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<Employee> employees = new ArrayList<>(); employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21))); employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22))); employees.add(new Employee(3l, "David", LocalDate.of(2018, Month.APRIL, 25))); employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23))); employees.add(new Employee(2l, "Edwin", LocalDate.of(2018, Month.APRIL, 24))); employees.sort(new AgeSorter()); System.out.println(employees); } }
Program output.
[ Employee [id=1, name=Alex, dob=2018-04-21], Employee [id=4, name=Brian, dob=2018-04-22], Employee [id=5, name=Charles, dob=2018-04-23], Employee [id=2, name=Edwin, dob=2018-04-24], Employee [id=3, name=David, dob=2018-04-25]]
That’s all for the ArrayList sort() method in Java.
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
Comparator Java Docs
Jagga
o2.getName().compareToIgnoreCase(o1.getName()) if o2.getName() is null, it will throw NPE.
Lokesh Gupta
Plz add an NPE check.
pango
return o1.getName().compareToIgnoreCase(o1.getName())
I think you have to change in :
return o1.getName().compareToIgnoreCase(o2.getName())
Lokesh Gupta
Thanks for reporting this typo. Much appreciated !!
Manu
Hi Lokesh,
In which class this sort() method present?