Java Hashmap entrySet() Example wpaccuracy

please click here for more wordpress cource

In Java, a HashMap is a collection that stores key-value pairs. The entrySet() method of the HashMap class returns a set of all key-value mappings contained in the map.

Here’s an example of using the entrySet() method to iterate over all entries in a HashMap:

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

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap
        Map<String, Integer> map = new HashMap<>();

        // Add some key-value mappings to the map
        map.put("John", 28);
        map.put("Alice", 35);
        map.put("Bob", 42);

        // Get a set of all key-value mappings in the map
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key + " = " + value);
        }
    }
}

In this example, we create a new HashMap called map and add three key-value mappings to it. We then use the entrySet() method to get a set of all key-value mappings in the map, and iterate over each entry in the set using a for-each loop.

Inside the loop, we use the getKey() and getValue() methods of the Map.Entry interface to retrieve the key and value of each entry. We then print out the key and value using System.out.println(). The output of this program would be:

John = 28
Alice = 35
Bob = 42

This demonstrates how to use the entrySet() method to iterate over all entries in a HashMap and access their keys and values.

You may also like...

Popular Posts

Leave a Reply

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