Introduction
In Java, a Map is a collection of key-value pairs. We can iterate over a Map using several ways. One of the ways is to iterate over the keys of the Map. In this article, we will discuss how to iterate over a Map of String objects in Java.
Using the keySet() method
The keySet() method of the Map interface returns a Set of keys contained in the Map. We can use the enhanced for loop to iterate over the Set of keys and get the corresponding values from the Map.
Example:
“`java Map
Output:
“` key1 = value1 key2 = value2 key3 = value3 “`
Using the entrySet() method
The entrySet() method of the Map interface returns a Set of Map.Entry objects, which contain both the key and the value. We can use the enhanced for loop to iterate over the Set of Map.Entry objects and get the key and the value from each Map.Entry object.
Example:
“`java Map
Output:
“` key1 = value1 key2 = value2 key3 = value3 “`
Using the forEach() method
The forEach() method of the Map interface takes a BiConsumer object, which accepts two arguments: the key and the value. We can pass a lambda expression to the forEach() method to iterate over the Map.
Example:
“`java Map
Output:
“` key1 = value1 key2 = value2 key3 = value3 “`
Conclusion
In this article, we discussed how to iterate over a Map of String objects in Java using the keySet(), entrySet(), and forEach() methods. These methods provide different ways to iterate over a Map and get the corresponding values. By using these methods, we can easily manipulate the data stored in a Map.