Last Updated:

Example of sorting using Java Comparable and Comparator

Java Comparable

First, let's look at an example of sorting primitive types and an example of sorting an array by an object in the program below:

As a result, we get the following output to the console:

So, now let's try to sort the array of objects of our own class:

The following is a code snippet for sorting an array of Employee objects:

Now let's run the program and get an error:

Why? The fact is that if a custom class in Java wants to use the built-in methods of sorting classes or , then it must implement the Comparable interface. This interface provides a method that is used by sort methods. You can see this for yourself just by looking at the implementation of classes or .ArraysCollectionscompareTo(T obj)StringDate

In order to avoid this error, we must override the method so that it returns a negative number, zero, or a positive integer if "this" object is less than, equal to, or greater than the object passed as an argument.compareTo(T obj)

After you implement the Comparable interface, the Employee class will change as follows:

Now that we run this code, we will get the output of the sorted array in a readable form to the console:

As you can see from the console output, the array of Employee objects is sorted by id in ascending order.

But in most real projects, you need several sorting options with different parameters, not just id. For example, you can sort employees by salary level or by age.

You can use the method to sort objects by only one field. For such situations, it is best to use a comparator.Comparable.compareTo(Object o)

The comparator method takes two objects as an argument and must be implemented in such a way as to return a negative number if the first argument is less than the second, zero if they are equal, and a positive number if the first argument is larger than the o1, Object o2)

Both interfaces and uses generics.ComparableComparator

Let's look at the comparator implementation in the Employee class:

All of the above implementations of the Comparator interface are anonymous classes.

We can use these comparators passing them as an argument to sort arrays or collections.

So, now we can sort any array or list of objects. To do this, we have to implement a Comparator for each specific field.

We can also create a separate class that implements the comparator interface and then use it.

Below is the final version with the comparable and Comparator interface implemented:

Now let's complicate our example and put our sort in a separate class and add another sorting condition:

The following is a separate class that implements the Comparator interface and will compare two objects by id, and if they are the same, by name:

Here's a test class where we use different ways to sort objects in Java:

Today we learned that and are powerful interfaces for sorting objects in