rspec/rules/S2864/java/rule.adoc
2022-02-04 16:28:24 +00:00

39 lines
920 B
Plaintext

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
[source,java]
----
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
[source,java]
----
public void doSomethingWithMap(Map<String,Object> map) {
for (Map.Entry<String,Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]