Java Utility Library

Java TreeMap - navigableKeySet() Method



The java.util.TreeMap.navigableKeySet() method returns a NavigableSet view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Syntax

public NavigableSet<K> navigableKeySet()

Here, K is the type of key maintained by the container.


Parameters

No parameter is required.

Return Value

Returns a navigable set view of the keys in this map.

Exception

NA.

Example:

In the example below, the java.util.TreeMap.navigableKeySet() method returns a NavigableSet view of the keys contained in the given map.

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");
    MyMap.put(105, "Sam");

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

    //creating a NavigableSet view of the keys
    NavigableSet<Integer> MySet = MyMap.navigableKeySet(); 

    //printing the set
    System.out.println("MySet contains: " + MySet);         
  }
}

The output of the above code will be:

MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam}
MySet contains: [101, 102, 103, 104, 105]

❮ Java.util - TreeMap