Home  >  Core Java

How to Iterate Map in Java

By Arvind Rai, January 31, 2022
We can iterate Java Map in following ways.
1. Use Map.entrySet that returns a collection view of Map.Entry.
2. Iterate over Map.entrySet using Iterator.
3. Iterate over Map.keySet for keys
4. Iterate over Map.values for values.
5. Iterate map using Map.forEach method.

Now let us discuss iterating Map with examples.



Using Map.Entry and Map.entrySet

The Map.Entry represents a key-value pair. The Map.entrySet returns a collection view of Map.Entry.
Set<Entry<Integer, String>> entrySet = map.entrySet(); 
Now let us create a HashMap that we will iterate.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Mahesh");
map.put(2, "Suresh");
map.put(3, "Nilesh"); 
Find the code to iterate Map using Map.Entry and Map.entrySet.
Set<Entry<Integer, String>> entrySet = map.entrySet();
for (Map.Entry<Integer, String> mapEntry : entrySet) {
  System.out.println(mapEntry.getKey() + " " + mapEntry.getValue());
} 
Output
1 Mahesh
2 Suresh
3 Nilesh 

Using Iterator and Map.entrySet

The Iterator iterates over a collection.
Iterator<Map.Entry<Integer, String>> mapEntryIte = map.entrySet().iterator();
while (mapEntryIte.hasNext()) {
  Entry<Integer, String> entry = mapEntryIte.next();
  System.out.println(entry.getKey() + " " + entry.getValue());
} 

Using Map.keySet and Map.values

Map.keySet
Set<K> keySet() 
Returns a Set of keys contained in this map.
Iterate over keys.
for (Integer key : map.keySet()) {
  System.out.println(key + " " + map.get(key));
} 

Map.values
Collection<V> values() 
Returns a Collection of the values contained in this map.
Iterate over values.
for (String v : map.values()) {
  System.out.println(v);
} 

Using forEach

The Map interface provides forEach as default method. The forEach method accepts BiConsumer as argument.
map.forEach((k,v) -> System.out.println(k +" : "+ v)); 
Output
1 : Mahesh
2 : Suresh
3 : Nilesh 

Iterate with var

The var keyword is the local variable type inference. It reduces the boilerplate code. With type inference, compiler can figure out the static types and we don’t have to write them.
for (var entry : map.entrySet()) {
  var key = entry.getKey();
  var value = entry.getValue();
  System.out.println(key + ": " + value);
} 

Reference

Interface Map
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us