首页 > 代码库 > How to Iterate Over a Map in Java?
How to Iterate Over a Map in Java?
1.Iterate through the "entrySet" like so:
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 }}
2.If you‘re only interested in the keys, you can iterate through the "keySet()" of the map:
Map<String, Object> map = ...;for (String key : map.keySet()) { // ...}
3.If you only need the values, use "value()":
for (Object value : map.values()) { // ...}
4.Finally, if you want both the key and value, use "entrySet()":
for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // ...}
Summary,If you need only keys or values from the map, use method #2 or method #3. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #1. Otherwise use method #4.
How to Iterate Over a Map in Java?
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。