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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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