map遍歷的幾種方式
1、通過map.entrySet( )遍歷:
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; i++) {
String s = "數字" + i;
map.put("zhi-" + i, s);
}
Set<Entry<String, String>> s = map.entrySet();
int size = s.size();
for(Map.Entry<String,String> entry:map.entrySet()) {
String value =entry.getValue();
String key = entry.getKey();
System.out.println("key:"+key+",value:"+value);
}
輸出結果為:
key:zhi-0,value:數字0
key:zhi-1,value:數字1
key:zhi-2,value:數字2
key:zhi-3,value:數字3
2、通過map.keySet()及map.value()遍歷:
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; i++) {
String s = "數字" + i;
map.put("zhi-" + i, s);
}
for (String key : map.keySet()) {
System.out.println(key);
}
for(String value:map.values()) {
System.out.println(value);
}
輸出結果為:
zhi-0
zhi-1
zhi-2
zhi-3
數字0
數字1
數字2
數字3
3、使用 Iterator遍歷:
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; i++) {
String s = "數字" + i;
map.put("zhi-" + i, s);
}
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> data = entries.next();
System.out.println("key:" + data.getKey() + ",value:" + data.getValue());
}
輸出結果為:
key:zhi-0,value:數字0
key:zhi-1,value:數字1
key:zhi-2,value:數字2
key:zhi-3,value:數字3
4、通過map.get(key)遍歷:
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; i++) {
String s = "數字" + i;
map.put("zhi-" + i, s);
}
for(String key:map.keySet()) {
String value = map.get(key);
System.out.println(key+" "+value);
}
輸出結果為:
zhi-0 數字0
zhi-1 數字1
zhi-2 數字2
zhi-3 數字3
map遍歷的幾種方式