1. 程式人生 > >遍歷HashMap的幾種方法

遍歷HashMap的幾種方法

有如下幾種方法:

1. 通過keyset

2. 通過 Map.entrySet().iterator()

3. 通過foreach ---- Map.entryset, 當hashmap很大時,推薦使用這種方式。

4. 通過Valueset

public static void main(String[] args) {
        HashMap<Integer, String> hashmap = new HashMap<>();
        hashmap.put(1,"gogo");
        hashmap.put(2,"wade");
        hashmap.put(3,"james");
        hashmap.put(4,"curry");
        // 1. 通過Map.keySet遍歷key和value:
        for (int key : hashmap.keySet()){
            System.out.println("key: "+ key + "; value: " + hashmap.get(key));
        }

        //2. 通過Map.entrySet使用iterator遍歷key和value:
        Iterator<Map.Entry<Integer, String>> it = hashmap.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());
        }

        //3. 通過Map.entrySet遍歷key和value
        for(Map.Entry<Integer, String> entry : hashmap.entrySet()){
            System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());
        }

        //4. 通過Map.values()遍歷所有的value,但不能遍歷key
        for (String value : hashmap.values()) {
            System.out.println("value: "+value);
        }
    }