JAVA traverses several implementations of the map code

  • 2020-04-01 02:41:03
  • OfStack


public static void main(String args[]) {
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("a", "A");
  map.put("b", "B");
  map.put("c", "C");
  //KeySet traversal
  Iterator<String> iterator = map.keySet().iterator();
  while (iterator.hasNext()) {
    String key = iterator.next();
    String value = (String) map.get(key);
    System.out.println(value);
  }
  for (String key : map.keySet()) {
    String value = (String) map.get(key);
    System.out.println(value);
  }
  //EntrySet traversal
  Iterator<Entry<String, Object>> iterator1 = map.entrySet().iterator();
  while (iterator1.hasNext()) {
    String value = (String) iterator1.next().getValue();
    System.out.println(value);
  }
  for (Entry<String, Object> entry : map.entrySet()) {
    String value = (String) entry.getValue();
    System.out.println(value);
  }
  //
  for (Object str : map.values()) {
    System.out.println(str);
  }
}

On efficiency:

If you use a HashMap

When traversing key and value simultaneously, the performance difference between keySet and entrySet methods depends on the specific conditions of key, such as complexity (complex objects), dispersion, conflict rate, etc. In other words, it depends on the overhead of a HashMap lookup value. An entrySet operation that takes out all keys and values at once has a performance overhead, and when this loss is less than the cost of HashMap lookup value, the performance advantage of entrySet will be realized. For example, in the above comparison test, when the key was the simplest numeric string, the keySet might instead be more efficient, taking 10% less time than the entrySet. EntrySet is generally recommended. Because when the key is simple, its performance may be slightly lower than that of the keySet, but it is manageable; As the key becomes more complex, the advantages of entrySet will be obvious. Of course, we can choose according to the actual situation
The keySet method is more appropriate when only traversing the key, because entrySet also takes out unused value, wasting performance and space. In the above test results, keySet took 23% less time than the entrySet method.
When traversing only value, the vlaues method is the best choice, and entrySet is slightly better than the keySet method.

If you use a TreeMap

Unlike HashMap, entrySet performs much better than keySet when traversing key and value at the same time. This is determined by the query efficiency of TreeMap, that is, the cost of finding value in TreeMap is higher than that of taking all the keys and values out of entrySet at once. Therefore, the entrySet method is highly recommended when traversing a TreeMap.


Related articles: