TreeMap keySet() method in java

Let’s learn TreeMap keySet() method in java.

TreeMap keySet() method in java

keySet() method of TreeMap class returns a Set view of the keys contained in this map.

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Syntax:

public Set<K> keySet()

Returns:

a set view of the keys contained in this map, sorted in ascending order.

Also read – TreeMap in java

Now let’s see example on TreeMap keySet() method.

import java.util.TreeMap;
public class TreeMapKeySetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(53, "mango");
      tm.put(62, "apple");
      tm.put(29, "grapes");
      tm.put(93, "banana");
      tm.put(98, "watermelon");
      System.out.println("Given TreeMap is: " + tm);
      // use keySet() to get set view of keys
      System.out.println("set is: " + tm.keySet());
   }
}


Output:

Given TreeMap is: {29=grapes, 53=mango, 62=apple, 93=banana, 98=watermelon}
set is: [29, 53, 62, 93, 98]


Let’s map Integer values to String keys.

import java.util.TreeMap;
public class TreeMapKeySetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      tm.put("mango", 53);
      tm.put("apple", 62);
      tm.put("grapes", 29);
      tm.put("banana", 93);
      tm.put("watermelon", 98);
      System.out.println("Given TreeMap is: " + tm);
      // use keySet() to get set view of keys
      System.out.println("set is: " + tm.keySet());
   }
}


Output:

Given TreeMap is: {apple=62, banana=93, grapes=29, mango=53, watermelon=98}
set is: [apple, banana, grapes, mango, watermelon]