What is the TreeMap.keySet() method in Java?

In this shot, we will learn how to use the TreeMap.keySet() method in Java. It is present in the TreeMap class inside the java.util package.

The TreeMap.keySet() method is used to create a new set and store the keys present in the TreeMap in sorted order.

Syntax

The syntax of the TreeMap.keySet() method is shown below:

Set<K> keySet();

Parameter

The TreeMap.keySet() method does not accept any parameters.

Return

The TreeMap.keySet() method returns a Set containing all the keys that are present in the TreeMap in increasing order.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> s = new TreeMap<Integer,String>();
s.put(2, "Learn");
s.put(12, "in-demand");
s.put(31, "tech");
s.put(18, "skills");
s.put(25, "on");
s.put(36, "Educative.io");
System.out.println("TreeMap mappings are: "+ s);
System.out.println("The set of keys in sorted order using keySet() method is:" + s.keySet());
}
}

Explanation:

  • In line 1, we imported the required package.

  • In line 2, we made a Main class.

  • In line 4, we made a main() function.

  • In line 6, we declared a TreeMap consisting of keys of type Integer and values of type String.

  • From lines 8 to 13, we inserted values in the TreeMap using the TreeMap.put() method.

  • In line 15, we displayed the mappings of the present in the TreeMap.

  • In line 17, we used the TreeMap.keySet() method to obtain the set with the same keys in sorted order as TreeMap and displayed it.

So, this is how to use the TreeMap.keySet() method in Java to create a Set view of all the keys present in the TreeMap.

Free Resources