TreeMap

Get Set view of TreeMap keys example

This is an example of how to get a Set view of the TreeMap keys. Getting a Set view of the TreeMap keys implies that you should:

  • Create a new TreeMap.
  • Populate the map with elements, with put(K key, V value) API method of TreeMap.
  • Invoke keySet() API method of TreeMap. The method returns a Set of all the keys contained in the TreeMap, that is backed by the TreeMap thus elements removed from the Set will also be removed from the originating TreeMap.
  • Note that it is not permitted to add an element to the resultant key set and an UnsupportedOperationException will be thrown in case we try to.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.TreeMap;
import java.util.Set;
 
public class KeySetTreeMap {
 
  public static void main(String[] args) {
 
    // Create a TreeMap and populate it with elements
    TreeMap treeMap = new TreeMap();
    treeMap.put("key_1","element_1");
    treeMap.put("key_3","element_3");
    treeMap.put("key_2","element_2");
 
    /*

Set keySet() returns Set of keys contained in TreeMap.

The key Set is backed by the TreeMap thus elements removed 

from the Set will also be removed from the originating TreeMap. 

Nevertheless it is not permitted to add an element to the 

resultant key set and java.lang.UnsupportedOperationException 

exception will be thrown in case we try to.
    */
    Set keySet = treeMap.keySet();
 
    System.out.println("TreeMap Keys : " + keySet);
 
    // Remove key_3 from Set
    keySet.remove("key_3");
 
    System.out.println("after removing key_3 from keySet, keySet contains : " + keySet + " treeMap contains : " + treeMap);
  }
}

Output:

TreeMap Keys : [key_1, key_2, key_3]
after removing key_3 from keySet, keySet contains : [key_1, key_2] treeMap contains : {key_1=element_1, key_2=element_2}

 
This was an example of how to get a Set view of the TreeMap keys in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button