Sort with Collections sort() Comparator

Sort with Collections sort() Comparator

Using Comparator, the sorting algorithm of Java can be customized. sort() method is overloaded that takes a Comparator object as parameter.

Two methods exist, with Collections class, for sorting elements. Following are the signatures.

  • static void sort(List list1): Sorts the list list1 into ascending order according to the natural sequence of the elements.
  • static void sort(List list1, Comparator comp1): Sorts the elements of list1 according to the order set by the Comparator object comp1.

The usage of first sort() method is illustrated earlier in "Sorting ArrayList with Collections sort()". Now let us go to the second sort() method using Comparator.

Note: It is advised to know first about interface Comparator and its methods like compare() etc. It is illustrated in interface Comparator, Comparator Example and Comparable vs. Comparator.

Example on Sort with Collections sort() Comparator

Sort with Collections sort() Comparator
Output screenshot on Sort with Collections sort() Comparator

A Student class is created, two instance variables marks and name are declared and values are assigned through a constructor. Two getter methods are declared with which Student marks and name are retrieved later.

Another class StudentSortByMarks is created to manipulate Student objects. Observe, the StudentSortByMarks class implements Comparator interface. The interface is designed to be generics; the Comparator compares or sorts only Student objects.

An ArrayList object studentList is created and added with a few elements of Student objects.

The StudentSortByMarks (that implements Comparator) is passed to sort() method. Now the sort() method sorts as per the compare() method (and not by its own style). The order elements can be changed.

After the studentList objects are sorted as per marks, the elements are printed using enhanced for loop.

Similar method sort() with Comparator operating on array elements is available at Sorting array elements with sort() and Comparator.

4 thoughts on “Sort with Collections sort() Comparator

Leave a Reply

Your email address will not be published. Required fields are marked *