Map集合遍历Entry()键值对对象方式
Map.Entry<K,V>:在Map接口中有一个内部接口Entry
作用:当Map集合一创建,那么就在Map集合中创建一个Entry对象,用来记录键与值(键值对对象,键与值得映射关系)—>结婚证
Map集合中遍历的第二种方法:使用Entry对象遍历
Map集合中的方法:
Set<map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系Set视图
可以分别找到键值getKey()和值getValue()
实现步骤:
Map<String,Integer> map = new HashMap<>();
map.put("张三",158);
map.put("李四",165);
map.put("王五",178);
-
使用Map集合中的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个set集合中
Set<Map.Entry<String, Integer>> set = map.entrySet();
-
遍历set集合,获取每一个Entry对象
Iterator<Map.Entry<String,String>> it = set.iterator();
-
使用Entry对象中的方法getKey()和getValue()获取键与值
while(it.hasNext()){ Map.Entry<String,String> entry = it.next(); String key = entry.getKey(); String value = entry.getValue(); System.out.println(key+"="+value); }
或使用增强for循环:
for(Map.Entry<String,String> entry : map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}