遍历HashMap的最佳方法

来源:互联网 发布:淘宝网双11 编辑:程序博客网 时间:2024/05/25 23:25

遍历HashMap的最佳方法

@(JAVA)[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        }    }}
原创粉丝点击