1. Introduction
The HashMap class in Java is a part of the java.util package and is used to store key-value pairs. To get a set view of the mappings contained in this map, the entrySet() method is used. This method returns a set of Map.Entry objects, which can be used to iterate over the HashMap. In this post, we will explore how to use the entrySet() method to get and display the key-value pairs of a HashMap.
2. Program Steps
1. Create a HashMap object and populate it with some key-value pairs.
2. Invoke the entrySet() method on the HashMap object to get a set view of the mappings.
3. Iterate over the set of Map.Entry objects and print each key-value pair.
3. Code Program
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapEntrySet {
public static void main(String[] args) {
// Step 1: Create a HashMap and populate it with key-value pairs
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Step 2: Invoke the entrySet() method to get a set view of the mappings
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// Step 3: Iterate over the set of Map.Entry objects and print each key-value pair
System.out.println("Key-Value pairs in the HashMap:");
for(Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
Key-Value pairs in the HashMap: One: 1 Two: 2 Three: 3
4. Step By Step Explanation
Step 1: A HashMap named map is created and populated with three key-value pairs. The keys are Strings, and the values are Integers.
Step 2: The entrySet() method is called on the map object. This method returns a Set of Map.Entry objects representing the mappings contained in this map. This Set is stored in the entrySet variable.
Step 3: An enhanced for loop is used to iterate over the Set of Map.Entry objects. Inside the loop, the getKey() and getValue() methods are called on each entry object to retrieve and print the key and value of each mapping in the HashMap.