遍历HashMap的最佳方法

遍历HashMap的最佳方法

@(工作笔记)[java]

stackoverflow上推荐的遍历hashMap的最佳方法:
详见github上的代码。

package org.ljh.javademo;

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

/*
 * stackoverflow上推荐的遍历hashmap的最佳方法。
 */

public class IterateHashMap {

    public static void main(String[] args) {

        Map map = new HashMap();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        printMap(map);

    }

    public static void printMap(Map mp) {
        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
    }

}

你可能感兴趣的:(遍历,HashMap)