keySet を使用して Map の要素にアクセスできます。
for( String currentKey : map.keySet() ){
String currentValue = map.get( currentKey );
}
以下は、 HashMap が4つの要素1,2,3、および4を持つ例です。これは、キーa、b、cおよびdで索引付けされています。 キーのリストは keySet メソッドを使用してアクセスされ、keySetはループされ、値は Map からアクセスされます。 キーと値の両方が出力に書き込まれます。
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