Se puede acceder a los elementos de un Mapa utilizando el keySet .
for( String currentKey : map.keySet() ){
String currentValue = map.get( currentKey );
}
Aquí hay un ejemplo con un HashMap con 4 elementos 1, 2, 3 y 4. Están indexados con las teclas a, b, c y d. Se accede a la lista de teclas utilizando el método keySet , luego se establece un bucle en keySet y se accede a los valores desde el Map . Tanto la clave como el valor están escritos en la salida.
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 );
}
}
}
a => 1
b => 2
c => 3
d => 4