遍历HashMap的最佳方法

xiaoxiao2021-02-28  100

遍历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 } } }
转载请注明原文地址: https://www.6miu.com/read-33721.html

最新回复(0)