Talking about several methods of traversing Map in Java

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 their respective advantages and disadvantages.

Initialize a map first

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

keySet values

If only the key or value of the map is needed, it is undoubtedly most convenient to use the keySet or values method of the map.

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

keySet get(key)

If you need to get key and value at the same time, you can get key first, and then get value through get(key) of map.

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

  // 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 the key and value at the same time. Generally speaking, the performance is better than the previous one, which is also the most commonly used 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

Iterator can be used to replace the foreach mentioned above. In fact, foreach is only supported in Java 5. Foreach seems to be written more concisely.

But Iterator also has its advantages: when traversing a map with foreach, if you change its size, it will report an error, but if you just delete elements, you can use Iterator's remote method to delete elements.

  // 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

Java 8 provides Lambda expression support. The grammar looks simpler and you can get key s and value s at the same time. However, after testing, the performance is lower than entrySet, so entrySet is more recommended.

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

Simple Performance Testing

With 100,000 data, a simple performance test is done. The data type is Integer. The map implementation chooses 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 map, the size of map, and the different implementation of map will affect the performance of traversal, so the test results are for reference only.

summary

If you're just getting key, or value, it's recommended to use keySet or values

EnySet is recommended if you need both key and value

Iterator is recommended if you need to delete elements during traversal

If you need to add elements in the traversal process, you can create a new temporary map to store the new elements. After traversal, you can put the temporary map into the original map.

Java learning and communication QQ group: 523047986 prohibit chatting, do not enter unless you like it!

Keywords: Java Lambda

Added by ashmo on Sun, 16 Jun 2019 03:07:08 +0300