[Reserved] 5 ways to traverse Map of Java


Disclaimer: This article is reprinted article, have adequate modified when reproduced, please attach the original source link and this statement is reproduced again.
Author: zhaoguhong (Zhao Gu Hong)
Source: http://www.cnblogs.com/zhaoguhong

Map Java, there are several ways to traverse, from the earliest iterator Iterator, began to support JDK 5 Enhanced for loop - that foreach, and then to the Lambda expressions JDK 8, let us look at the specific usage and its advantages and disadvantages.

1 traversing through keySet () or values ​​() method

If you only need to get Map key or value, through the Map keySet()or values()method is undoubtedly the most convenient:


public class TestMap {
    /**
     * Map 的扩容比较消耗性能, 因此若能确定存储数据的大小,
     * 在初始化时指定初始容量是一个不错的实践技巧
     */
    private static Map<Integer, Integer> map = new HashMap<>(16);

    /** keySet 获取 key */
    public void testKeySet() {
        for (Integer key : map.keySet()) {
          System.out.println(key);
        }
    }
    /** values 获取 value */
    public void testValues() {
        for (Integer value : map.values()) {
            System.out.println(value);
        }
    }
}

2 keySet retrieve the values ​​of the get (key)

If you need to obtain the key and value, you can get through the first key, and then through the Map of get(key)obtaining corresponding value.

Note: This method is not optimal, it is generally not recommended.

    /** keySet get(key) 获取key and value */
    public void testKeySetAndGetKey() {
        for (Integer key : map.keySet()) {
            System.out.println(key + ":" + map.get(key));
        }
    }

3 traversed by entrySet

By entrySet Map of traverse, you can also get the key and value at the same time.

The most commonly used method is a method Map traverse, in many cases, the performance is better than the second type.

  /** 
    * entrySet 获取 key 和 value, Entry 是 Map 内部存储数据的逻辑容器
    */ 
  public void testEntry() {
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      System.out.println(entry.getKey() + ":" + entry.getValue());
    }
  }

4 traverse through the iterator Iterator

Several traversal methods used above are enhanced for loop - foreach, this is only the beginning of JDK 5 features.

foreachAlthough it looks very simple operation, but there is one disadvantage: when traversing Map, if you change its size, concurrent modifications will throw an exception , but only if you need to remove elements while traversing the Map, it can use the Iterator remove()method Removing elements:

    /** Iterator 获取 key 和 value */
    public void testIterator() {
        Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, Integer> entry = it.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
            // 删除元素
            // it.remove();
        }
    }

5 traversed by Lambda expressions

JDK 8 provides Lambda support, it looks more concise syntax, you can get the key and value at the same time.

However, after a simple test, Lambda expressions Map traverse speed is lower than entrySet traverse way, so more is recommended entrySet to traverse Map.

    /** Lambda 获取key and value */
    public void testLambda() {
        map.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
    }

6 Summary - Traverse Map of practical advice

(1) only if the acquired key or value, recommended keySet()or values()methods;

(2) If you need to obtain the key and value, recommended entrySet;

(3) If you need to remove elements during traversal recommended Iterator;

(4) If you need to add elements in the traversal process, you can create a new temporary Map storage element, after the end of the traverse, then added to the original interim Map Map.

Copyright Notice

This article belongs to original author, if infringement, please contact the blogger, certainly removed immediately.

To reprint, please indicate the original link in the apparent position of the article page, or else your own risk.

Guess you like

Origin www.cnblogs.com/shoufeng/p/11774640.html