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);
}
本文介绍了Map集合遍历Entry键值对对象的方式,讲解了Map.Entry接口的作用,即记录键值对的映射关系,并详细说明了使用Entry对象遍历Map集合的步骤,包括通过entrySet()方法获取Set视图,以及如何通过getKey()和getValue()获取键与值。
2254

被折叠的 条评论
为什么被折叠?



