package com.itheima.demo01.Map;java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;code
/*對象
Map集合的第一種遍歷方式:經過鍵找值的方式 Map集合中的方法: Set<K> keySet() 返回此映射中包含的鍵的 Set 視圖。 實現步驟: 1.使用Map集合中的方法keySet(),把Map集合全部的key取出來,存儲到一個Set集合中 2.遍歷set集合,獲取Map集合中的每個key 3.經過Map集合中的方法get(key),經過key找到value
*/
public class Demo02KeySet {get
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); } System.out.println("-------------------"); //使用加強for遍歷Set集合 for(String key : map.keySet()){ //3.經過Map集合中的方法get(key),經過key找到value Integer value = map.get(key); System.out.println(key+"="+value); } }
}it