ArrayList Object Sort in Java with Comparable and Comparator

Sorting ArrayList that contains custom objects need a different approach than, a ArrayList with primitive types. Sorting ArrayList with basic types is easy.

When it has custom objects, we need to specify what you really mean by sorting. For example, a User object might have properties age and name. When you are sorting on Users, do you want to sort by age or name?

This is why we need to have our own way to mention the sorting mechanism.

Two approaches could be taken here.

Sort with Comparable Interface

If you can implement Comparable interface on the Class to be sorted, it will force you to have compareTo() method. Here is where you mention your sorting mechanism.

The following code shows sorting with Comparable Interface. We are sorting objects of User class.

User class:

Main:

Output:

See the result sorted by age.

 

Sort with Comparator

So why we need Comparator? If you look in to the Comparable mechanism, you might have noticed that you can do it only for a single property and that has to be an integer.

With Comparator we have even more flexibility and we can compare based on various properties.

In the following example, we will sort User objects by age and name.

Approach is to create two comparators one for age and another for name. In the Collections.sort, we will pass appropriate Comparator.

User class:

Main:

 

Output:

 

Click Here to Leave a Comment Below

Leave a Reply: