Way2Java

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();
    stones.add("pearl");
    stones.add("diamond");
    stones.add("ruby");
    stones.add("emerald");
    stones.add("topaz");

    Comparator comp1 = Collections.reverseOrder();

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

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



Output screenshot on Comparator Example Java

ArrayList stones = new ArrayList();
stones.add(“pearl”);

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".