可以使用 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