How to Iterate Over a Map in Java?

Posted 但行好事 莫问前程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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?的主要内容,如果未能解决你的问题,请参考以下文章

How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for lo

如何迭代pandas dataframe的行

How Hulu Uses InfluxDB and Kafka to Scale to Over 1 Million Metrics a Second

Iterate over slices of a string

如何在Ruby中遍历数组

python 来自http://stackoverflow.com/questions/12325608/iterate-over-a-dict-or-list-in-python/12325691#