先初始一下map的数据
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "11");
map.put(2, "22");
map.put(3, "33");
map.put(4, "44");
目前有三种遍历方法
知识回顾:Set集合无序、不可重复, 有时用于重复值过滤
1.遍历key
//通过Map.keySet遍历key
Set<Integer> set = map.keySet();// 返回键的集合
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
int key = (Integer) it.next();
String value = (String) map.get(key);
System.out.println(key + "----" + value);
}
2.遍历value
//Map.values()遍历所有的value
for (String str : map.values()) {
System.out.println("value= " + str);
}
3.遍历键值对
//使用iterator遍历key和value[方便删除元素]
Iterator<Map.Entry<Integer, String>> it2 = map.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<Integer, String> entry = it2.next();
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue());
}
//Map.entrySet遍历key和value
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue());
}