Java TreeMap keySet() Method Example

The entrySet() method of java.util.TreeMap class returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa whereas keySet() method will return a Set view of the keys contained in this map. The set’s iterator returns the keys in ascending order.

Signature

public Set<K> keySet()

This method returns a Set 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.

Example

The following example shows the usage of java.util.TreeMap.keySet() method.

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class KeySetMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to populate elements to the TreeMap
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(1,"Element1");
        treeMap1.put(5,"Element5");
        
        //get the entrySet of treeMap1
        Set  set1 = treeMap1.keySet();
        //Print the elements of treeMap1
        System.out.println("**Elements of treeMap1**");
        for (Integer key : set1) 
        {
            System.out.print("Key : "+key);
            System.out.println(" Value : "+treeMap1.get(key));
        }
    }
}

Output

**Elements of treeMap1**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 5 Value : Element5

Leave a Reply

Your email address will not be published. Required fields are marked *