Home » Core Java » util » LinkedHashMap » Get Set view of LinkedHashMap keys example

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Get Set view of LinkedHashMap keys example

In this example we shall show you how to get a Set view of the LinkedHashMap keys. To get a Set view of the LinkedHashMap keys one should perform the following steps:

  • Create a new LinkedHashMap.
  • Populate the linkedHashMap with elements, with put(K key, V value) API method of LinkedHashMap.
  • Invoke keySet() API method of LinkedHashMap. The method 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.
  • 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,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.LinkedHashMap;
import java.util.Set;
 
public class KeySetLinkedHashMap {
 
  public static void main(String[] args) {
 
    // Create a LinkedHashMap and populate it with elements
    LinkedHashMap linkedHashMap = new LinkedHashMap();
    linkedHashMap.put("key_1","value_1");
    linkedHashMap.put("key_2","value_2");
    linkedHashMap.put("key_3","value_3");

    /* 

Set keySet() operation returns a Set containing all keys in LinkedHashMap. 

The key set is backed by the LinkedHashMap thus elements removed from the 

key set will also be removed from the originating LinkedHashMap. 

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 = linkedHashMap.keySet();

    System.out.println("keySet contains : " + keySet);

    keySet.remove("key_2");

    System.out.println("after removing key_2 from keySet, keySet contains : " + keySet + " linkedHashMap contains : " + linkedHashMap);
    
  }
}

Output:

keySet contains : [key_1, key_2, key_3]
after removing key_2 from keySet, keySet contains : [key_1, key_3] linkedHashMap contains : {key_1=value_1, key_3=value_3}

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments