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
        }
    }
  • 相关阅读:
    cmcc_simplerop
    WeiFenLuo.winFormsUI.Docking.dll的使用
    MySQL转换Oracle的七大注意事项
    icsharpcode
    详细介绍IIS7基于WAS 部署WCF服务《收藏》
    Win2008 IIS7日期格式更改方法 《转》
    SVCUtil使用说明(生成代理类)《收藏》
    Oracle中的高效语句
    WCF配置文件全攻略《收藏》
    设计高效合理的MySQL查询语句
  • 原文地址:https://www.cnblogs.com/lintong/p/4365734.html
Copyright © 2011-2022 走看看