keySet() vs values() vs entrySet() method in Java

In this post, we will discuss the difference between keySet(), values(), and entrySet() methods of the Map’s interface in Java.

 
The java.util.Map interface provides three methods keySet(), values() and entrySet(), which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings respectively. The collection returned by these methods are backed by the map, so any changes to the map are reflected in the collection, and vice-versa. Also if the map is structurally modified during the iteration except through the iterator’s remove() method, the results of the iteration are undefined. These are covered below in detail:

 

1. keySet() method

The keySet() method returns a Set view of the keys contained in the map. There are several ways to print all keys present in a Map using keySet() method as shown below. These are also discussed in detail here.

 

Download   Run Code

 

2. values() method

The values() method returns a Collection view of the values contained in the map. There are several ways to print all values present in a Map using values() method as shown below:

 

Download   Run Code

 

3. entrySet() method

The keySet() method returns a Set view of the mappings contained in this map. There are several ways to print all keys present in a Map use keySet() method as shown below. These are also discussed in detail here.

 

Download   Run Code

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of