package cn.itcast.day12.demo03;
/**
* @author admin
* @version 1.0.0
* @ClassName Demo05.java
* @Description TODO
* @createTime 2021年09月25日 16:07:00
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Map集合遍历的第二种方式:使用Entry对象遍历
* Map集合中的方法:
* Set<Map,Entry<k,v>> entrySet(),返回此映射中包含的映射关系的Set视图
*实现步骤:
* 1.使用Map集合中的方法EntrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
* 2.遍历Set集合,获取每一个Entry对象
* 3.使用Entry对象中的getKey()和getValue()获取键与值
*/
public class Demo05 {
public static void main(String[] args) {
//创建集合对象
HashMap<String, Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("杨颖",165);
map.put("林志玲",188);
// 1.使用Map集合中的方法EntrySet(),
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// 2.使用加强for循环 遍历Set集合,获取每一个Entry对象
for (Map.Entry<String, Integer> entry : entrySet) {
//3.使用Entry对象中的getKey()和getValue()获取键与值
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key +" !!! "+ value);
/**
* 林志玲 !!! 188
* 赵丽颖 !!! 168
* 杨颖 !!! 165
*/
}
System.out.println("==============");
Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+ " = " + value);
/**
* 林志玲 = 188
* 赵丽颖 = 168
* 杨颖 = 165
*/
}
}
}
Map集合遍历键值对方式
最新推荐文章于 2024-06-26 18:22:55 发布