Sort an Array using Comparator

Posted on Updated on

Comparator is an interface which comes under java.util package is useful to impose a total ordering on a collection of elements (Objects) of an array into ascending or descending order.

Where T represents the type of elements (Objects) compared by the Comparator.

The Comparator interface contains a method compare() that should be implemented in such a way that the two object should be compared using comparedTo() method as –

The compareTo() method returns a postive value if  x>y and a negative value if x<y whereas it returns 0(zero) if x==y (double equal sign). This logic can be applied to a group of objects when we want to arrange them in ascending/descending order.

Let have example that shows sorting using comparator

 

Test Class

 

Output:

 

Stay tuned for more updates !

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.