Java HashMap entrySet()

The syntax of the entrySet() method is:

hashmap.entrySet()

Here, hashmap is an object of the HashMap class.


entrySet() Parameters

The entrySet() method does not take any parameter.


entrySet() Return Value

  • returns a set view of all the entries of a hashmap

Note: The set view means all entries of the hashmap are viewed as a set. Entries are not converted to a set.


Example 1: Java HashMap entrySet()

Output

HashMap: {Pant=150, Bag=300, Shoes=200}
Set View: [Pant=150, Bag=300, Shoes=200]

In the above example, we have created a hashmap named prices. Notice the expression,

prices.entrySet()

Here, the entrySet() method returns a set view of all the entries from the hashmap.

The entrySet() method can be used with the for-each loop to iterate through each entry of the hashmap.

Example 2: entrySet() Method in for-each Loop

Output

HashMap: {One=1, Two=2, Three=3}
Entries: One=1, Two=2, Three=3, 

In the above example, we have imported the java.util.Map.Entry package. TheĀ Map.Entry is the nested class of theĀ Map interface. Notice the line,

Entry<String, Integer> entry :  numbers.entrySet()

Here, the entrySet() method returns a set view of all the entries. The Entry class allows us to store and print each entry from the view.


Recommended Reading