How to iterate Map in Java
In this topic, we will learn to iterate the Map in Java. A Map is an interface that is available in java.util package. These are the following ways to iterate the Map:
• Iterate Map Using Iterator
• Iterate Map Using for each loop
• Iterating Map using keySet() and values() methods
• Iterate Map using forEach() method
Iterate Map Using Iterator
Example
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class Test
{
public static void main(String[] arg)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Peter");
map.put(2, "Robert");
map.put(3, "William");
map.put(4, "John");
// Using iterator
Iterator<Map.Entry<Integer, String>> itr = gfg.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<Integer, String> entry = itr.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
}
Output
Key = 1, Value = Peter
Key = 2, Value = Robert
Key = 3, Value = William
Key = 4, Value = John
Iterate Map Using for each loop
Example
import java.util.Map;
import java.util.HashMap;
public class Test
{
public static void main(String[] arg)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Peter");
map.put(2, "Robert");
map.put(3, "William");
map.put(4, "John");
for(Map.Entry<Integer,String> entry:map.entrySet())
{
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
}
Output
Key = 1, Value = Peter
Key = 2, Value = Robert
Key = 3, Value = William
Key = 4, Value = John
Iterating Map using keySet() and values() methods
Example
import java.util.Map;
import java.util.HashMap;
public class Test
{
public static void main(String[] arg)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Peter");
map.put(2, "Robert");
map.put(3, "William");
map.put(4, "John");
// using keySet() for iteration over keys
for (Integer key : map.keySet())
System.out.println("key: " + key);
// using values() for iteration over values
for (String value : map.values())
System.out.println("value: " + value);
}
}
Output
key: 1
key: 2
key: 3
key: 4
value: Peter
value: Robert
value: William
value: John
Iterate Map using forEach() method
Example
import java.util.Map;
import java.util.HashMap;
public class Test
{
public static void main(String[] arg)
{
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Peter");
map.put(2, "Robert");
map.put(3, "William");
map.put(4, "John");
// forEach(action) method to iterate map
map.forEach((k,v) -> System.out.println("Key = "
+ k + ", Value = " + v));
}
}
Output
Key = 1, Value = Peter
Key = 2, Value = Robert
Key = 3, Value = William
Key = 4, Value = John
Conclusion
In this topic, we learnt about how to iterate Map in several ways in Java.
Leave your thought here
Your email address will not be published. Required fields are marked *