Skip to content

Java Sort Objects using Comparator Example

Java sort objects using Comparator example shows how to sort custom objects using a Comparator by the object properties in ascending or descending order.

How to sort objects using a Comparator in Java?

In order to sort custom objects by its properties, we need to implement the compare method of the Comparator interface.

Comparator interface has the compare method which must be implemented by the class implementing the Comparator interface.

To sort objects in ascending order, this method should return 0 if the two objects are equal, a positive integer if the object1 is greater than object2 and a negative integer if object1 is less than object2.

For this example, we are going to sort ArrayList of Employee objects. We will sort the employee according to their age in ascending order.

Output

How to sort objects in descending order using Comparator in Java?

In the above example we returned zero for equal age, a positive value if the age of employee1 is greater than employee2 and a negative value if the age of employee1 is less than the age of employee2. If you want to sort the Employee objects in descending order, you need to inverse the return values.

That means you need to return a negative value if employee1’s age is greater than employee2’s age and a positive integer if employee1’s age is less than employee2’s age property.

The compare method needs to be changed as given below.

Output

This example is a part of the Java Comparator tutorial with examples. Please also check out the ArrayList in Java tutorial to know more.

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

About the author

Leave a Reply

Your email address will not be published.