java HashMap的四種獲取key,value的方式


初學java不久,我覺得這樣將學到的東西總結下來非常好,如果有一天有些地方忘記了

可以回過頭來翻看,不用來回的找,非常好,也是一個很好的習慣 

今天主要將記錄獲取hashMap的key,value的幾種方式  

代碼如下:

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

public class MapTest {

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("1", "張三");
        map.put("2", "李四");
        map.put("3", "王五");
        map.put("4", "趙六");
        //1,通過map.keyset遍歷輸出集合
        for (String s : map.keySet()) {
            System.out.println("key: " + s + " value: " + map.get(s));
        }
        System.out.println("====================================");
        //第二種只遍歷鍵或者值,通過加強for循環
        for (String s1 : map.keySet()) {//遍歷map的鍵
            System.out.println("鍵key :" + s1);
        }
        for (String s2 : map.values()) {//遍歷map的值
            System.out.println("值value :" + s2);
        }
        System.out.println("====================================");
        //第三種方式Map.Entry<String, String>的加強for循環遍歷輸出鍵key和值value
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key: " + entry.getKey() + ",value: " + entry.getValue());
        }
        System.out.println("====================================");
        //第四種Iterator遍歷獲取,然后獲取到Map.Entry<String, String>,再得到getKey()和getValue()
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            System.out.println("key: " + next.getKey() + ",value: " + next.getValue());
        }
    }
}

這是簡單的獲取,可以根據自己項目的邏輯需求來進行相應的調整.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM