Easy Tutorial
❮ String Compare String Uppercase ❯

Java HashMap entrySet() Method

Java HashMap

The entrySet() method returns a Set view of the mappings contained in this map.

The syntax for the entrySet() method is:

hashmap.entrySet()

Note: hashmap is an object of the HashMap class.

Parameter:

Return Value

Returns a Set view of the mappings contained in this map.

Note: The Set view means that all the key-value pairs in the HashMap are treated as a set collection.

Example

The following example demonstrates the use of the entrySet() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Return the set view of the mappings
        System.out.println("Set View: " + sites.entrySet());
    }
}

Executing the above program outputs:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Set View: [1=Google, 2=tutorialpro, 3=Taobao]

The entrySet() method can be used with a for-each loop to iterate over each mapping in the HashMap.

Example

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

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

        // Create a HashMap
        HashMap&lt;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 in the HashMap
        System.out.print("Entries: ");

        // entrySet() returns a set view of all the mappings in the HashMap
        // The for-each loop accesses each mapping in the set view
        for(Entry&lt;String, Integer> entry: numbers.entrySet()) {
            System.out.print(entry);
            System.out.print(", ");
        }
    }
}

Executing the above program outputs:

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

Java HashMap

❮ String Compare String Uppercase ❯