This post discusses basic methods to loop over Map in Java. Using following methods, you can loop over any Map implementation such as HashMap, LinkedHashMap, TreeMap etc…
Initialization
Lets initialize a HashMap containing country code and country name as below.
// Initialize Hashmap
Map<String, String> countryCodes = new HashMap<String, String>();
// Load Hashmap
countryCodes.put("AUS", "Australia");
countryCodes.put("CAN", "Canada");
countryCodes.put("PAK", "Pakistan");
countryCodes.put("INR", "India");
Method 1: Iterate and remove value from Map
THIS IS THE ONLY METHOD WHICH CAN ITERATE OVER MAP AND REMOVE ELEMENT FROM UNDERLYING MAP INSTANCE WHILE ITERATION. All other methods can iterate over Map elements, but they does not allow removing element while iteration.
//Method 1: Iterate and remove value from Map
Iterator<Map.Entry<String, String>> mapIterator = countryCodes.entrySet().iterator();
while (mapIterator.hasNext()) {
Map.Entry<String, String> entry = mapIterator.next();
System.out.println("Key: "+ entry.getKey() + " => Value : "+ entry.getValue());
if(entry.getKey().equalsIgnoreCase("PAK"))
mapIterator.remove();
}
// Console
/*
Key: AUS => Value : Australia
Key: INR => Value : India
Key: PAK => Value : Pakistan
Key: CAN => Value : Canada
*/
Method 2: Loop over key and values
If you need key and value of Map elements in your loop, then use this method.
// Method 2: Loop over key and values
for(Map.Entry<String, String> entry : countryCodes.entrySet())
{
System.out.println("Key: "+ entry.getKey() + " => Value : "+ entry.getValue());
}
// Console
/*
Key: AUS => Value : Australia
Key: INR => Value : India
Key: CAN => Value : Canada
*/
Method 3: Loop over keys
This method iterate over keys of a HashMap.
// Method 3: Loop over keys
for(String key : countryCodes.keySet())
{
System.out.println("Key: "+ key);
}
// Console
/*
Key: AUS
Key: INR
Key: CAN
*/
Method 4: Loop over values
Use this method if you need only value of Map elements in your loop.
// Method 4: Loop over values
for(String value : countryCodes.values())
{
System.out.println("Value: "+ value);
}
// Console
/*
Value: Australia
Value: India
Value: Canada
*/