rspec/rules/S2864/java/rule.adoc

25 lines
728 B
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When only the keys from a map are needed in a loop, iterating the ``++keySet++`` makes sense. But when both the key and the value are needed, it's more efficient to iterate the ``++entrySet++``, which will give access to both the key and value, instead.
== Noncompliant Code Example
----
public void doSomethingWithMap(Map<String,Object> map) {
for (String key : map.keySet()) { // Noncompliant; for each key the value is retrieved
Object value = map.get(key);
// ...
}
}
----
== Compliant Solution
----
public void doSomethingWithMap(Map<String,Object> map) {
for (Map.Entry<String,Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
}
----