码迷,mamicode.com
首页 > 编程语言 > 详细

How to Iterate Over a Map in Java?

时间:2016-09-01 12:31:07      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

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?

标签:

原文地址:http://www.cnblogs.com/garfieldcgf/p/5829070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!