zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    课后作业10.13
    大道至简:软件工程实践者的思想 读后感
    课程作业01
    动手动脑10.13
    动手动脑
    js矢量图类库:Raphaël—JavaScript Library
    OSGi bundle之间互相通信的方法
    OSGi bundle 与 fragment
    Spring.DM web 开发环境搭建
    Spring.DM版HelloWorld
  • 原文地址:https://www.cnblogs.com/lintong/p/4365734.html
Copyright © 2011-2022 走看看