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

In this shot, we will discuss how to use the SortedMap.keySet() method in Java.

SortedMap.keySet() methods are present in the SortedMap interface inside the java.util package.

The SortedMap.keySet() method is used to create a new set and store the key elements of the TreeMap in sorted order.

Parameter

The SortedMap.keySet() method doesn’t take any parameter.

Return

The SortedMap.keySet() method returns:

  • Set: A set with the same keys as that of the map in increasing order.

Code

Let’s look at the below code snippet.

import java.util.*;
class Main
{
public static void main(String[] args)
{
SortedMap<Integer, String> s = new TreeMap<Integer,String>();
s.put(2,"Welcome");
s.put(12,"to");
s.put(31,"the");
s.put(18,"world");
s.put(25,"of");
s.put(36,"java");
System.out.println("SortedMap 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 SortedMap consisting of Integer type keys and String type values.
  • From lines 8 to 13, we inserted values in the Hashtable by using the TreeMap.put() method.
  • In line 15, we displayed the mappings present in the SortedMap.
  • In line 17, we used the SortedMap.keySet() method to obtain the set with the same keys in the sorted order as SortedMap and displayed it.

In this way, we can use the SortedMap.keySet() method in Java.

Free Resources