Map集合的第一种遍历方式:通过键找值的方式
Map集合中的方法:
Set keySet()返回此映射中包含的键的Set视图
实现步骤:
1、使用Map集合的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中
2、遍历Set集合,获取Map集合中的每一个key
3、通过Map集合的方法get(key),通过key找到value
public class Demo02KeySet {
public static void main(String[] args) {
//创建Map对象
Map<String,Integer> map=new HashMap<>();
map.put("赵丽颖",168);
map.put("杨颖",165);
map.put("林志颖",178);
//1、使用Map集合的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中
Set<String> set = map.keySet();
// 2、遍历Set集合,获取Map集合中的每一个key
//使用迭代器遍历Set集合
Iterator<String> it = set.iterator();
while (it.hasNext()){
String key = it.next();
//3、通过Map集合的方法get(key),通过key找到value
Integer value = map.get(key);
System.out.println("key:"+value);
}
System.out.println("-----------");
//增强for循环遍历set集合
for (String key : set) {
//3、通过Map集合的方法get(key),通过key找到value
Integer value = map.get(key);
System.out.println("key:"+value);//key:168 key:165 key:178
}
//简化增强for循环
for (String key : map.keySet()) {
//3、通过Map集合的方法get(key),通过key找到value
Integer value = map.get(key);
System.out.println("key:"+value);key:168 key:165 key:178
}
}
}