【Java】Entry鍵值對對象獲取Map的鍵值對

Entry鍵值對對象

Map.Entry<K,V>:在Map接口中有一個內部接口Entry

作用:當Map集合一創建,那麼就會在Map集合中創建一個Entry對象,用來記錄鍵與值(鍵值對對象,鍵與值的映射關係)-“結婚證”

 

Map.Entry:結婚證

 

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 DemoEntry {

public static void main(String[] args) {

Map<String,Integer> map = new HashMap<>();

map.put("趙麗穎",168);

map.put("楊穎",165);

map.put("林志玲",178);

Set<Map.Entry<String,Integer>> entry = map.entrySet();

Iterator<Map.Entry<String,Integer>> it = entry.iterator();

while(it.hasNext()){

Map.Entry<String,Integer> entry1 = it.next();

String key = entry1.getKey();

Integer value = entry1.getValue();

System.out.println(key+":"+value);

}

System.out.println("========================");

for(Map.Entry<String,Integer> entry1: entry){

String key = entry1.getKey();

Integer value = entry1.getValue();

System.out.println(key+":"+value);

}

}

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章