How to loop on a Map elements in Java

Elements from a Map can be accessed using the keySet.

Syntax:

for( String currentKey : map.keySet() ){
	String currentValue = map.get( currentKey );
}

Example:

Here is an example with an HashMap with 4 elements 1, 2, 3 and 4. That are indexed with the keys a, b, c and d. The list of the keys is accessed using the keySet method, then the keySet is looped on and the values accessed from the Map. Both the key and the value are written in the output.

import java.util.HashMap;
import java.util.Map;

public class MapLoop {

    public static void main(String[] argv) {
	
	// Create the map
	Map<String, Integer> map = new HashMap<String, Integer>();

	// Add the values
	map.put( "a" , 1);
	map.put( "d" , 4);
	map.put( "c" , 3);
	map.put( "b" , 2);
	
	// Loop on all the elements in the map
	for( String currentKey : map.keySet() ){
	    int currentValue = map.get( currentKey );
	    
	    System.out.println( currentKey + " => " + currentValue );
	}
    }
}

The output will be:

	
a => 1
b => 2
c => 3
d => 4
	

References:

Class HashMap

Share this article:

Recent Comments