hashmap的遍历方法

How to iterate over the entries of a Map?

What is the order of iteration - if you are just using Map, then strictly speaking, there are no ordering guarantees. So you shouldn't really rely on the ordering given by any implementation. However, the SortedMap interface extends Map and provides exactly what you are looking for - implementations will aways give a consistent sort order.

NavigableMap is another useful extension - this is a SortedMap with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place - you might be able to find the specific entry you are after using the higherEntrylowerEntryceilingEntry, or floorEntry methods. The descendingMap method even gives you an explicit method of reversing the traversal order.

If you're only interested in the keys, you can iterate through the keySet() of the map:

1 Map<String, Object> map = ...;
2 
3 for (String key : map.keySet()) {
4     // ...
5 }

If you only need the values, use values():

1 for (Object value : map.values()) {
2     // ...
3 }

Finally, if you want both the key and value, use entrySet():

1 for (Map.Entry<String, Object> entry : map.entrySet()) {
2     String key = entry.getKey();
3     Object value = entry.getValue();
4     // ...
5 }

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator  . However, changing item values is OK (see Map.Entry).

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
    }
}
原文地址:https://www.cnblogs.com/lintong/p/4365734.html