This post will discuss how to sort an array of objects using the Comparable and Comparator interface in Java.

1. Using Comparable

To sort an array of objects using the Arrays.sort method in Java, we can have the class implement the Comparable interface, which then imposes a natural ordering on its objects.

If an object implements the Comparable interface, it needs to override its abstract method compareTo(), which compares an object with the specified object. The value returned by the compareTo() method decides the position of the object relative to the specified object.

If compareTo() returns a

  • negative value, the object is less than the specified object.
  • zero, the object is equal to the specified object.
  • positive value, the object is greater than the specified object.

Here’s how we sort the array of the Student object using the Comparable interface, where the array is first ordered by age and then by name.

Download  Run Code

Output:
[{name='Joe', age=10}, {name='John', age=15}, {name='Dan', age=20}, {name='Sam', age=20}]

2. Using Comparator

A Comparator is a comparison function that imposes a total ordering on some collection of objects and allows precise control over the sort order when passed to the Arrays.sort method.

If an object implements the Comparator interface, it needs to override the abstract method compare(), which compares its two arguments for order. The value returned by the compare() method decides the position of the first object relative to the second object.

If compare() returns a

  • negative value, the first argument is less than the second.
  • zero, the first argument is equal to the second.
  • positive value, the first argument is greater than the second.

 
In the following example, we obtain a Comparator that compares Student objects first by their age and then by name.

Download  Run Code

Output:
[{name='Joe', age=10}, {name='John', age=15}, {name='Dan', age=20}, {name='Sam', age=20}]

 
The above code can be easily shortened using lambda expressions:

 
Or even shorter:

 
 
We can also use the Comparator.thenComparing() method, which effectively combines two comparisons into one:

That’s all about sorting an array of objects in Java.