Comparator Example Java

After knowing the fundamentals of interface Comparator, let us make a small example. ArrayList elements are printed in reverse order using Comparator.

Example code on Comparator Example Java
import java.util.*;
public class ComparatorExample
  public static void main(String args[])
    ArrayList stones = new ArrayList();

    Comparator comp1 = Collections.reverseOrder();

    System.out.println("Default order of stones: " + stones);

    Collections.sort(stones, comp1); 
    System.out.println("Stones in reverse order: " + stones);

Comparator Example Java
Output screenshot on Comparator Example Java

ArrayList stones = new ArrayList();

An ArrayList object stones is created and added a few elements with add() method.

Comparator comp1 = Collections.reverseOrder();

To get an object of Comparator, comp1, the reverseOrder() method of Collections is used.

Collections.sort(stones, comp1);

Always Comparator and Comparable objects are used with combination of overloaded Collections.sort() method. In the above statement, the sort() method sorts the elements as per order imposed by the Comparator, comp1.

Also read Comparable vs. Comparator for more examples and tutorial.

"Comparator Example Java" requires good practice to use in development.

Pass your comments or suggestions to improve the quality of this tutorial "Comparator Example Java".

4 thoughts on “Comparator Example Java”

  1. Abhinav Joshi

    Sir can we not use a String array instead of ArrayList. In this code i am first trying to sort by length then alphabetically. Please help.

    import java.util.*;
    * @author Joshi
    class MyComparator implements Comparator{
    public int compare(String o1, String o2) {
    if (o1.length() > o2.length()) {
    return 1;
    } else if (o1.length() < o2.length()) {
    return -1;
    return o1.compareTo(o2);
    public class Two_Way_Sort
    public static void main(String[] args)
    //String[] st1 = {"yogesh","pankaj","ram","ila","zu","devendra"};
    ArrayList names = new ArrayList();
    Collections.sort(names, new MyComparator());
    System.out.println("Sorted List : "+names);

  2. what comparator can do operations we can do by using also comparable then why using comparator interface i also seen example but i din’t understand

    we can do also sort elements like id ,name with comparable

Leave a Comment

Your email address will not be published.