Map String Object Iteration In Java

How to Iterate Through Map and List in Java? Example attached (Total 5
How to Iterate Through Map and List in Java? Example attached (Total 5 from crunchify.com

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 map = new HashMap<>(); map.put(“key1”, “value1”); map.put(“key2”, “value2”); map.put(“key3”, “value3″); for (String key : map.keySet()) { String value = map.get(key); System.out.println(key + ” =” + value); } “`

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 map = new HashMap<>(); map.put(“key1”, “value1”); map.put(“key2”, “value2”); map.put(“key3”, “value3”); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + ” =” + value); } “`

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 map = new HashMap<>(); map.put(“key1”, “value1”); map.put(“key2”, “value2”); map.put(“key3”, “value3″); map.forEach((key, value) -> { System.out.println(key + ” =” + value); }); “`

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.

Posted in Map

Leave a Reply

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