Iterating on Map
entries is more efficient than iterating on the keys and asking for their respective values. The additional lookup operation is saved.
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}
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}