How to Iterate Over a Map in Java?(如何遍历Map)

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.

posted @ 2016-09-01 11:21  但行好事-莫问前程  阅读(358)  评论(0编辑  收藏  举报