Collections

Java sort ArrayList using Comparator example

Java sort ArrayList using Comparator example shows how to sort ArrayList using custom comparator. It also shows how to sort ArrayList by object properties in descending order.

How to sort ArrayList using Comparator?

We are going to store Student objects in the ArrayList as given below.

We want to sort the ArrayList by student’s total marks in ascending order. In order to sort ArrayList by object properties, we will need to create a custom comparator which will compare objects based on their properties.

Class implementing Comparator interface must implement the compare method which returns positive integer, zero or negative integer values.

If we want to sort ArrayList by student’s total marks in ascending order, compare method needs to return positive integer if object1’s total marks is greater than object2’s total marks. It should return 0 if both object’s marks are equal. And it should return negative integer is object1’s total marks are less than object2’s total marks as given below.

ArrayList can be sorted by custom comparator using sort method of Collections class.

This method sorts List or ArrayList by specified custom comparator.

Here is the complete example.

Output

How to sort ArrayList using Comparator in descending order?

In above example, we returned positive, zero and negative values for greater, equal and less object values respectively. In order to sort the ArrayList in descending order, we need to inverse the return values.

That is, we need to return negative value if object1’s total marks property is greater than object2’s total marks, zero for equal, and positive value if object1’s total marks property is less than object2’s total marks as given below.

Output

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.