首页 > 编程语言 > 详细

How to Iterate Over a Map in Java?

时间:2016-09-01 12:28:43      阅读:111      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!