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

 

posted on 2019-02-12 21:11  qqzhulu  阅读(186)  评论(0编辑  收藏  举报