Java HashMap KeySet – Get all Keys example

This example shows how to get all the keys of the HashMap using the keySet method. This example also shows how to iterate all keys of HashMap using the keySet method.

How to get all keys of the HashMap using the keySet method?

The keySet method of the HashMap class returns a Set view of all the keys contained in the map object.

Example:

Output

Important Note:

The keySet method returns a Set view of all the keys. This view is backed by the original HashMap object. It means that any changes you make in this set are reflected in the map and vice versa as given in the below example.

Output

How to iterate over all keys of HashMap?

Get the set view of all the keys of the map object using the keySet method as given above. Once you have the key set, obtain the Iterator object using the iterator method of the set. Then use the hasNext and next method to iterate over all the keys of the HashMap.

Output

You can also remove a key while iterating over the HashMap key set using the remove method of the iterator. Please remember that the corresponding key-value pair will be removed from the HashMap object too as the set is backed by the original HashMap object.

Output

Note:

The set obtained via the keySet method does not support add and addAll operations. If the original map is modified while the iteration is in progress except through the remove method of an iterator, the iteration result is undefined.

This example is a part of the Java HashMap tutorial with examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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