Talk about several ways to traverse Map in java

Posted by spdwrench on Wed, 19 Jun 2019 19:10:15 +0200

There are many ways to traverse a map in java, from the earliest Iterator to the foreach supported by Java 5 to Java 8 Lambda. Let's look at the specific usage and advantages and disadvantages of each.

Initialize a map first

public class TestMap {
  public static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
}

keySet values

If only the map's key or value is needed, using the map's keySet or values method is undoubtedly the most convenient

  // KeySet Gets key
  public void testKeySet() {
    for (Integer key : map.keySet()) {
      System.out.println(key);
    }
  }
  // values get value
  public void testValues() {
    for (Integer value : map.values()) {
      System.out.println(value);
    }
  }

keySet get(key)

If you need to get both key and value, you can get the key first, then get the value through get(key) of the map

It should be noted that this method is not the best choice and is generally not recommended.

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

entrySet

By traversing the map entrySet, you can also get key s and value s at the same time, which generally outperforms the previous one, which is also the most common traversal method

  // entrySet gets key and value
  public void testEntry() {
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      System.out.println(entry.getKey() + ":" + entry.getValue());
    }
  }

Iterator

For each of the foreachs above, Iterator can be used instead. In fact, foreach is only supported in Java 5. Foreach seems to be written more concisely

However, Iterator also has advantages: when traversing a map with foreach, if you change its size, you will get an error, but if you just delete the element, you can use Iterator's remove method to delete the element

  // Iterator entrySet gets key and 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(); delete elements
    }
  }

Lambda

java8 provides Lambda expression support. The syntax looks simpler and you get key s and value s at the same time. However, after testing, the performance is lower than that of entrySet, so entrySet is preferred.

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

Simple Performance Test

A simple performance test was done with 100,000 pieces of data, the data type is Integer, the map implementation selects HashMap

  static {
    for (int i = 0; i < 100000; i++) {
      map.put(i, 1);
    }
  }

The test results are as follows:

KeySet:            392
Values:            320
keySet get(key):   552
entrySet:          465
entrySet Iterator: 508
Lambda:            536

It should be noted that the type of data stored in the map, the size of the map, and the different implementations of the map all affect traversal performance, so the test results are for reference only

summary

If you just get the key, or value, the keySet or values method is recommended

EnySet is recommended if both key and value are required

Iterator is recommended if you need to delete elements during traversal

If you need to add elements during traversal, you can create a new temporary map to store the new elements, wait until the traversal is complete, and then put the temporary map in the original map

Author: Zhangoguhong (Zhao Guhong)

Source: http://www.cnblogs.com/zhaoguhong/

Copyright of this article is shared by the author and the blog park. Please indicate where it is reproduced

Topics: Java Lambda