User Brian
Brian
Level 41

How to use keySet method in java.util.Map

Published in the Java Developer group
If you need to get all the keys that your Map contains, you can use the really handy java.util.HashMap.keySet() method. In this article, we will explain how it works. As you know, the HashMap class implements the Map interface, so in the examples we are going to use the HashMap keySet() method.

HashMap keySet() method signature and operating principle

Set<K> keySet() method returns a Set view of the keys that are contained in this map. The feature of this Set collection, that keeps the keys, is that there cannot be duplicate elements in it. The set is backed by the map. That means that if something was changed in the map, it is reflected in the set, and vice-versa. For example, you can remove items from this set, and the keys and their corresponding values are automatically removed from the map, but you can’t add new items in it.

HashMap keySet() examples

Let’s create a HashMap with names of our friends and their digital keys and then print out the Set of the keys using HashMap keySet() method.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("myKeySet of the map: "+myKeySet);
The output is:
keys of the map: [1, 2, 3, 4, 5]
Besides the java.util.HashMap.keySet() method in Java there is an entrySet() method, it also returns a Set, but this set contains key-value pairs. Here is an example with both java.util.HashMap.keySet() and java.util.HashMap.entrySet() methods:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
       System.out.println("keys and values of the map: " );
       for( Map.Entry e : myHashMap.entrySet()){
           System.out.println(e.getKey() + " : " + e.getValue());
       }
   }
}
Here is the output:
keys of the map: [1, 2, 3, 4, 5] keys and values of the map: 1 : John 2 : Ivy 3 : Ricky 4 : Andrew 5 : Alex
Now let’s try to remove an element from the keySet and make sure it affects our original HashMap.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
      myKeySet.remove(4);
       System.out.println("myHashMap after removing an element from myKeySet: " + myHashMap);
       System.out.println("keys of the map: " + myKeySet);
   }
}
The output is:
keys of the map: [1, 2, 3, 4, 5] myHashMap after removing an element from myKeySet: {1=John, 2=Ivy, 3=Ricky, 5=Alex} keys of the map: [1, 2, 3, 5]
As you can see, we removed a key “4” from the Set, and it resulted in removing a pair “4-Alex” from our HashMap. Now let’s try to add a key to keySet():

import java.util.HashMap;
       import java.util.Map;
       import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
       myKeySet.add(7);

   }
}
In this case we’ll get an Exception, because our keySet connected to our hashMap:
keys of the map: [1, 2, 3, 4, 5] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractCollection.add(AbstractCollection.java:251) at KeySetDemo.main(KeySetDemo.java:20) Process finished with exit code 1
How to use keySet method in java.util.Map - 1
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION