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
        }
    }
  • 相关阅读:
    Graceful degradation versus progressive enhancement
    表现与数据分离
    避免写出IE Bug
    js控制元素的显示与隐藏
    EntityManager方法简介
    JPA EntityManager详解(一)
    Springmvc中 同步/异步请求参数的传递以及数据的返回
    JPA详解
    单向关系中的JoinColumn
    Hibernate一对多和多对一关系详解 (转载)
  • 原文地址:https://www.cnblogs.com/lintong/p/4365734.html
Copyright © 2011-2022 走看看