Collections

Java Sort Objects using Comparator Example

Java sort objects using Comparator Example shows how to sort custom objects using Comparator. This example also shows how to sort objects in descending order by object properties using comparator.

How to sort objects using Comparator in Java?

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

Comparator interface has 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 two argument objects are equal, positive integer if the object1 is greater than object2 and negative integer if object1 is less than object2.

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

Output

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

In above example we returned zero for equal age, positive value if age of employee1 is greater than employee2 and negative value if age of employee1 is less than 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 negative value if employee1’s age is greater than employee2’s age and positive integer if employee1’s age is less than employee2’s age property.

Only compare method needs to be changed 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.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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