Map集合的第一种遍历方式:键找值
我自己的理解就是用Map集合中keyset()方法把Map中所有的key取出来放到set集合中,然后遍历set。
public class demo {
public static void main(String[] args) {
//创建Map集合
Map<String,Integer> map = new HashMap<>();
map.put("张三",10);
map.put("李四",20);
map.put("王五",66);
map.put("赵六",88);
//把Map集合中的key全部取出来,存储到set集合中
Set<String> set = map.keySet();
//使用迭代器遍历set集合
Iterator<String> it = set.iterator();
while(it.hasNext()){
String key = it.next();
//通过key,找到value
Integer value = map.get(key);
System.out.println(key+"="+value);
}
}
}
输出的结果是:
李四=20
张三=10
王五=66
赵六=88
Map集合的第二种遍历方式:使用entry对象遍历
public class demo {
public static void main(String[] args) {
//创建Map集合
Map<String,Integer> map = new HashMap<>();
map.put("张三",10);
map.put("李四",20);
map.put("王五",66);
map.put("赵六",88);
//使用Map中的方法entrySet(),把Map集合中多个entry对象取出来,存储到一个set集合中。
Set<Map.Entry<String, Integer>> set = map.entrySet();
//使用增强for遍历set集合
for(Map.Entry<String,Integer> entry:set){
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"="+value);
}
}
}
输出的结果是:
李四=20
张三=10
王五=66
赵六=88