Java Utility Library

Java TreeMap - comparator() Method



The java.util.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.

Syntax

public Comparator<? super E> comparator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

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

Exception

NA.

Example:

In the example below, the java.util.TreeMap.comparator() method returns the comparator which returns null as the keys of given map is already sorted according to the natural ordering system.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating the map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 

    //creating comparator
    Comparator comp = MyMap.comparator();
    
    //printing comparator value
    System.out.println("Comparator value is: "+ comp);  
  }
}

The output of the above code will be:

MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo}
Comparator value is: null

❮ Java.util - TreeMap