學習Map.Entry

Map.Entry的定義
        Map的entrySet()方法返回一個實現Map.Entry接口的對象集合。集合中每個對象都是底層Map中一個特定的鍵/值對。通過這個集合的迭代器,獲得每一個條目(唯一獲取方式)的鍵或值並對值進行更改。

Map.Entry中的常用方法如下所示:

       (1) Object getKey(): 返回條目的關鍵字
  (2) Object getValue(): 返回條目的值
  (3) Object setValue(Object value): 將相關映像中的值改爲value,並且返回舊值
 

package blog;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestEntry {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("1", "蘋果");
        map.put("2", "香蕉");
        map.put("3", "桃子");
        Iterator<Map.Entry<String,String>> iterator=map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> stringEntry=iterator.next();
            System.out.println("Key:"+stringEntry.getKey()+" Value:"+stringEntry.getValue());
        }
        //第二種遍歷方法
        for(Map.Entry<String,String> stringEntry:map.entrySet()){
            System.out.println("Key:"+stringEntry.getKey()+" Value:"+stringEntry.getValue());

        }
      
    }
}
輸出結果
Key:1 Value:蘋果
Key:2 Value:香蕉
Key:3 Value:桃子

Process finished with exit code 0

有時候我們想要雙重循環遍歷Map裏面的Key或者是Value,這個時候我們用迭代器是完成不了這個功能的。究其原因是因爲,迭代器只能一直向前走。

那麼我們可以用以下代碼完成雙重循環這個功能

package blog;

import java.util.*;

public class TestEntry {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("1", "蘋果");
        map.put("2", "香蕉");
        map.put("3", "桃子");
        map.put("11", "蘋果1");
        map.put("22", "香蕉2");
        map.put("33", "桃子3");
        List<String> list=new ArrayList<>(map.values());
        for(int i=0;i<list.size();i++){
            for(int j=i+1;j<list.size();j++){
                System.out.println(list.get(j));
            }
        }
    }
}

 

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