Inefficient map entry iteration Low

Iterating on Map entries is more efficient than iterating on the keys and asking for their respective values. The additional lookup operation is saved.

Detector ID
java/iterate-on-map-entries@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1public void iterateOnKeySetUsingValuesNoncompliant(Map<String, String> map) {
2    // Noncompliant: iterate the set of keys and get the value of each key from the map.
3    for (String name : map.keySet())
4        System.out.println("Value: " + map.get(name));
5}

Compliant example

1public void iterateOnEntrySetCompliant(Map<String, String> map) {
2    // Compliant: iterate the set of map entries.
3    for (Map.Entry<String,String> entry : map.entrySet())
4        System.out.println("Key: " + entry.getKey() +
5                ", Value: " + entry.getValue());
6}