

In this tutorial, we learned how to iterate a Map in Java. Likewise, we can use the values() method to fetch a Collection containing all the values of the map. Then, we can simply use a for-loop to traverse the Set. We can get a set containing all the keys by using the Map.keySet() method. However, we can iterate through the keys and values separately. In all the above sections, we were traversing the keys and values parallelly. forEach(e -> (e.getKey() + "->" + e.getValue())) ġ04->Harry Iterating Keys and Values Separately

Next, we will use the forEach() method on each Map.Entry and fetch its key and value. We will again use the entrySet() method and then create a stream from this set. We can use the Stream API to loop through a Map. Map.forEach((key, value) -> (key + "->" + value))
Java for loop hashmap code#
The code below demonstrates this technique. This is probably the simplest approach of all, and we can use this to iterate a Map in a single line of code. (key + "->" + map.get(key)) ġ04->Harry Using forEach() and Lambda Expressions(Java 8) We can iterate through each key and retrieve the corresponding value by using the get() method. (key + "->" + value) ġ04->Harry Using keySet() method of MapĪs the name suggests, the Map.keySet() method returns a set containing all the keys of the map instance. Then, we can use the hasNext() and next() methods to loop through each element and fetch it. We will first get an Iterator instance using the iterator() method on the entry set. We can also traverse the Set returned by Map.entrySet() by using iterators. The following code shows its demonstration. We can iterate through this Set and use the getKey() and getValue() methods to fetch the key and value from each Map.Entry. The Map.entrySet() method returns a collection view(a Set) of our map, and each element of the returned set is of type Map.Entry. We can apply the following techniques to iterate any map(HashMap, LinkedHashMap, or a TreeMap). It is used to store a single key-value mapping. However, there are other ways of traversing a map. We cannot directly iterate over a Map using iterators, as it is not a true collection. The Map is an interface in Java that is used to store key-value pairs.
