Java treemap comparator() method example

Let’s learn java treemap comparator() method example.

Java treemap comparator() method example

TreeMap comparator() method returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.

Let’s see example on TreeMap comparator() method for natural ordering.

import java.util.Comparator;
import java.util.NavigableMap;
import java.util.TreeMap;
public class TreemapComparatorExample 
{
   public static void main(String[] args) 
   {
      NavigableMap<Integer, String> nm = new TreeMap<Integer, String>();
      // populating tree map
      nm.put(101, "apple"); 
      nm.put(102, "banana"); 
      nm.put(103, "apricot"); 
      nm.put(104, "blackberry"); 
      nm.put(105, "avocado"); 
      // printing TreeMap 
      System.out.println("TreeMap: " + nm);
      // using comparator() method
      Comparator c = nm.comparator();
      // print comparator value
      System.out.println("Comparator value: " + c);
   }
}


Output:

TreeMap: {101=apple, 102=banana, 103=apricot, 104=blackberry, 105=avocado}
Comparator value: null


Now let’s learn above example in reverse order.

import java.util.Collections;
import java.util.Comparator;
import java.util.NavigableMap;
import java.util.TreeMap;
public class TreemapComparatorExample 
{
   public static void main(String[] args) 
   {
      NavigableMap<Integer, String> nm = new TreeMap<Integer, String>(Collections.reverseOrder());
      // populating tree map
      nm.put(101, "apple"); 
      nm.put(102, "banana"); 
      nm.put(103, "apricot"); 
      nm.put(104, "blackberry"); 
      nm.put(105, "avocado"); 
      // printing TreeMap 
      System.out.println("TreeMap: " + nm);
      // using comparator() method
      Comparator c = nm.comparator();
      // print comparator value
      System.out.println("Comparator value: " + c);
   }
}


Output:

TreeMap: {105=avocado, 104=blackberry, 103=apricot, 102=banana, 101=apple}
Comparator value: java.util.Collections$ReverseComparator@15db9742


Also read – java overview