TreeSet comparator() method in java

Let’s learn TreeSet comparator() method in java.

TreeSet comparator() method in java

comparator() method of TreeSet class returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.

Syntax:

public Comparator<? super E> comparator()

Also read – TreeSet in java

Now let’s see example on TreeSet comparator() method.

import java.util.TreeSet;
public class TreeSetComparatorMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> comp = new TreeSet<Integer>();
      ts.add(5);
      ts.add(6);
      ts.add(7);
      ts.add(8);
      ts.add(9);
      ts.add(10);
      // use comparator
      comp = (TreeSet)ts.comparator();
      if(comp != null)
      {
         for(Integer element : comp)
         {
            System.out.println(element + " ");
         }
      }
      else
      {
         System.out.println("TreeSet comparator value: " + comp);
         System.out.println("Hence it is using natural ordering.");
      }
   }
}


Output:

TreeSet comparator value: null
Hence it is using natural ordering.