keySet 을 사용하여 Map 의 요소에 액세스 할 수 있습니다.
for( String currentKey : map.keySet() ){
String currentValue = map.get( currentKey );
}
다음은 4 개의 원소 1, 2, 3, 4로 구성된 HashMap 을 가진 예제입니다. 이것은 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