Map集合的四种遍历方式
- 迭代器遍历(不错)
Map<Integer, String> map = new HashMap<>();
map.put(1, "刘备");
map.put(2, "张飞");
map.put(3, "关羽");
map.put(4, "诸葛亮");
Set<Integer> keySet = map.keySet();
Iterator<Integer> iterator = keySet.iterator();
while (iterator.hasNext()) {
System.out.println(map.get(iterator.next()));
}
- 使用entrySet加增强for遍历(一般)
Map<Integer, String> map = new HashMap<>();
map.put(1, "刘备");
map.put(2, "张飞");
map.put(3, "关羽");
map.put(4, "诸葛亮");
for (Map.Entry<Integer, String> entries:map.entrySet()){
System.out.println(entries.getKey()+"=>"+entries.getValue());
}
- foreach和Lambda表达式遍历(真棒)
Map<Integer, String> map = new HashMap<>();
map.put(1, "刘备");
map.put(2, "张飞");
map.put(3, "关羽");
map.put(4, "诸葛亮");
map.forEach((k,v)->{
System.out.println(k+"=>"+v);
});
- 普通for遍历(感觉不太行啊)
Map<Integer, String> map = new HashMap<>();
map.put(1, "刘备");
map.put(2, "张飞");
map.put(3, "关羽");
map.put(4, "诸葛亮");
Set<Integer> keySet = map.keySet();
Object[] keys =keySet.toArray();
for (int i = 0; i < keys.length; i++) {
System.out.println(map.get(keys[i]));
}