创建一个Map
Map< String, String > map = new HashMap<>();
map.put("map1", "this is map1");
map.put("map2", "this is map2");
map.put("map3", "this is map3");
一、通过entrySet
public void traverseByEntry( Map<String, String> map){
System.out.println("通过entrySet,key: ");
for( Map.Entry<String, String> entry : map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key: "+key+", value: "+value);
}
}
输出结果为:
通过entrySet:
key: map3, value: this is map3
key: map2, value: this is map2
key: map1, value: this is map1
二、通过keySet
public void traverseByKey( Map<String, String> map){
System.out.println("通过keySet:");
for( String key : map.keySet()){
String value = map.get(key);
System.out.println("key: "+key+", value: "+value);
}
}
输出结果为:
通过keySet:
key: map3, value: this is map3
key: map2, value: this is map2
key: map1, value: this is map1
三、直接遍历Value
public void traverseValue( Map<String, String> map){
System.out.println("直接遍历Value:");
for( String value : map.values()){
System.out.println("value: "+value);
}
}
输出结果为:
直接遍历Value:
value: this is map3
value: this is map2
value: this is map1