Map集合的四種遍歷方式

Map集合遍歷

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

public class Traversal {


    public static void mapTraversal1(Map<String,Integer> map){
        System.out.println("第一種:通過Map.keySet遍歷key和value");

        //Set<K> keySet() 返回集合中包含的鍵的Set視圖。
        for (String s : map.keySet()) {
             Integer n = map.get(s);//得到每個 key 對應用的值 value
             System.out.println(s + " : " + n);
        }
    }

    public static void mapTraversal2(Map<String,Integer> map){
        System.out.println("第二種:通過Map.entrySet使用iterator遍歷key和value");

        //Set<Map.Entry<K,V>> entrySet() 返回集合中包含的映射的Set視圖
        //Iterator<E> iterator() 返回此集合中的元素的迭代器。
        //Iterator<E> 沒有關於元素返回順序的保證(除非這個集合是提供保證的某個類的實例)
        Iterator<Map.Entry<String,Integer>> iterator = map.entrySet().iterator();

        //boolean hasNext() 如果迭代具有更多的元素,則返回 true
        //即如果 next() 返回一個元素而不是拋出一個異常,則返回 true
        while (iterator.hasNext()) {
            Map.Entry<String,Integer> entry = iterator.next();//E next()返回迭代中的下一個元素
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    public static void mapTraversal3(Map<String,Integer> map){
        System.out.println("第三種:通過Map.entrySet遍歷key和value");

        //Set<Map.Entry<K,V>> entrySet() 返回集合中包含的映射的Set視圖
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    public static void mapTraversal4(Map<String,Integer> map) {
        System.out.println("第四種:通過Map.values()遍歷所有的value,但不能遍歷key");
        //Collection<V> values() 返回此集合中包含的值的Collection視圖
        for (Integer v : map.values()) {
            System.out.println("value= " + v);
        }
    }
}

程序測試

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("dbca",1);
        map.put("abcd",2);
        map.put("efgh",3);
        map.put("dbca",4);
        map.put("abcd",2);
        map.put("hhhh",3);
        mapTraversal1(map);
        mapTraversal2(map);
        mapTraversal3(map);
        mapTraversal4(map);
    }

測試結果:
在這裏插入圖片描述

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