java.util.HashMap keySet()

Description :

On this document we will be showing a java example on how to use the keySet() method of HashMap Class. Basically this method is to get all the keys that the HashMap contains. This method can strategically be used to iterate to all the contents of the HashMap which means this is a good way to get the values. Personally prefer using this method rather than using Iterator in getting the values inside the HashMap because its simplicity. Beside its simplicity there is an interesting behavior of this method which we would be discussing on the latter part of this article.

In dealing with HashMap methods, as a general rule you must always watch out for Generics such that if we have declared our map like HashMap<Integer,String> map = new HashMap<Integer,String>();  then the return keys are expected to be Integer object type or its subclass. The keySet method returns a Set. The Set class as of java 5 is already using Generics too, thus if we have done the same as above code, then the type parameters of our Set should also be Integer. To clarify this here is an example Set<Integer> set = map.keySet() . If you are still confused, please go through the concept of generics from the official documentation.

Important notes for keySet() method:

  • specified by keySet in interface Map<K,V>
  • overrides keySet in class AbstractMap<K,V>

Method Syntax :

public Set<K> keySet()

Parameter Input :

[table]
DataType|Parameter|Description
N/A|N/A|N/A
[/table]

Method Returns :

The keySet() method retyurns a set view of the keys contained in this map.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Java Code Example :

Below is a java code demonstrates the use of keySet() method of HashMap class. The example presented might be simple however it shows the behavior of the keySet() method.

Sample Output :

Running the above java example of the usage of HashMap keySet() method will give the following output:

HashMap keySet example output

HashMap keySet example output

There would be two output on the console when you try to run the provided example. First, the initial value of keys were printed and the next one are the new set of keys after we added additional key-value mapping on our HashMap. At first glance this is a straightforward example but did you notice that we have not invoked the keySet after we have put additional key on our HashMap and yet the new key were added to the setOfkeys. This is the inherent behavior of keySet() method when you modify the HashMap object the set would also be modified. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Suggested Reading List :

The following are the recommended reading materials for further understanding of HashMap

References :