Skip to content

Java sort ArrayList using Comparator example

Java sort ArrayList using comparator example shows how to sort an ArrayList using a custom comparator by object properties in ascending or descending order.

How to sort ArrayList using Comparator?

We are going to store the 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 the ArrayList by object properties, we will need to create a custom comparator that will compare objects based on their properties.

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

For our requirement, the 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.

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

This method sorts the List or ArrayList by the specified custom comparator.

Here is the complete example.

Output

How to sort ArrayList in descending order?

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

That is, we need to return a 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

This example is a part of the Java ArrayList tutorial.

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

About the author

Leave a Reply

Your email address will not be published.