1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public static void function() {
Map<String, Integer> map=new HashMap<String,Integer>();
map.put("a", 1);
map.put("b", 2);
//获取map的键值对Set集合
Set<Map.Entry<String,Integer>> set=map.entrySet();
//获取该Set的迭代器对象
Iterator<Map.Entry<String, Integer>> iterator=set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry=iterator.next();
//调用Entry对象的方法获取键和值
String key=entry.getKey();
Integer value=entry.getValue();
System.out.println("Key:"+key+"---------"+"Value:"+value);
// 输出:Key:a---------Value:1 Key:b---------Value:2
}
//foreach
for (Map.Entry<String, Integer> entry : set) {
System.out.println("Key:"+entry.getKey()+"---------"+"Value:"+entry.getValue());
// 输出:Key:a---------Value:1 Key:b---------Value:2
}
}
|