Map集合的遍历有两种方式:
- 将Map集合转为Set集合
Set<Map.Entry<K,V>> entrySet()
- 获取Map集合中的所有的key,所有的key是一个set集合
Set<K> keySet()
一、将Map集合转为Set集合
Map<Integer,String> maps = new HashMap<>();
maps.put(1,"张三");
maps.put(2,"李四");
maps.put(3,"王五");
maps.put(4,"赵六");
maps.put(5,"孙七");
Set<Map.Entry<Integer,String>> set = maps.entrySet();
for (Map.Entry<Integer,String> node:set) {
System.out.println(node);
}
Iterator<Map.Entry<Integer,String>> it2 = set.iterator();
while (it2.hasNext()){
Map.Entry<Integer,String> node = it2.next();
System.out.println(node);
}
二、获取Map集合中的所有的key,根据key遍历集合
Map<Integer,String> maps = new HashMap<>();
maps.put(1,"张三");
maps.put(2,"李四");
maps.put(3,"王五");
maps.put(4,"赵六");
maps.put(5,"孙七");
Set<Integer> keys = maps.keySet();
for (Integer i:keys) {
System.out.println(i+"="+maps.get(i));
}
Iterator<Integer> it = keys.iterator();
while (it.hasNext()){
Integer key = it.next();
String value = maps.get(key);
System.out.println(key+"="+value);
}