Skip to content

Instantly share code, notes, and snippets.

@wutianlong
Last active June 2, 2016 09:14
Show Gist options
  • Save wutianlong/87cb653d25b195df816f to your computer and use it in GitHub Desktop.
Save wutianlong/87cb653d25b195df816f to your computer and use it in GitHub Desktop.
HashMap 遍历最佳方案,移除元素避免异常
遍历HashMap中元素的最佳方法是什么?
解决方案
这样遍历entrySet:
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment