Java TreeMap comparator() Method Example

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

Signature

public Comparator<? super K> comparator()

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

Example

The following example shows the usage of java.util.TreeMap.comparator() method.

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class ComparatorMethodTreeMapExample 
{
    public static void main(String args[])
    {
     // create an empty TreeMap
        TreeMap<Integer,String> treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Printing the elements of the TreeMap
        System.out.println("**Elements of \"treeMap1\"**");
        System.out.println("Size of treeMap1 is : "+treeMap1.size());
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
        //Using comparator()
        Comparator comp = treeMap1.comparator();
        //Lets print the comparator following natural order
        System.out.println("Value of Comparator : "+comp);
    }
}

Output

**Elements of "treeMap1"**
Size of treeMap1 is : 4
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 4 Value : Element4
Key : 5 Value : Element5
Value of Comparator : null

Leave a Reply

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