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()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // return set view of mappings
    System.out.println("Set View: " + prices.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

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
    public static void main(String[] args) {

        // Creating a HashMap
        HashMap<String, Integer> numbers = new HashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("HashMap: " + numbers);

        // access each entry of the hashmap
        System.out.print("Entries: ");

        // entrySet() returns a set view of all entries
        // for-each loop access each entry from the view
        for(Entry<String, Integer> entry: numbers.entrySet()) {
            System.out.print(entry);
            System.out.print(", ");
        }
    }
}

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