Java Map的幾種遍歷方式

模擬數據:

Map<String, String> map = new HashMap<>();
    map.put("A","a");
    map.put("B","b");
    map.put("C","c");
    map.put("D","d");

1.for-each循環map.entrySet()----可以取key和value

for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }

2.for-each循環中遍歷keys。

for (String key : map.keySet()) {
            System.out.println("Key = " + key);
        }

3.for-each循環中遍歷values。

for (String value : map.values()) {
            System.out.println("Value = " + value);
        }

4.使用Iterator遍歷

Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }

 

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