Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(4, "e");
//第一种:通过Map.keySet遍历key和value
for (Integer key : map.keySet()) {
//根据键获得值
String value = map.get(key);
System.out.println(" key="+key+" value="+value);
}
//推荐 尤其容量大时
//第二种:通过Map.entrySet遍历key和value
for (Entry<Integer, String> s : map.entrySet()) {
System.out.println("key="+s.getKey()+" value="+s.getValue());
}
//第三种:通过Map.values遍历所有value
for (String s : map.values()) {
System.out.println(s);
}
//第四种:通过Map.entrySet使用iterator遍历key和value
//迭代器
Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Entry<Integer, String> next = it.next();
System.out.println("key="+next.getKey()+" value="+next.getValue());
}
评论 (0)