rspec/rules/S2864/java/rule.adoc

60 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
`Map` is an object that maps keys to values. A map cannot contain duplicate keys, which means each key can map to at most one value.
2021-04-28 16:49:39 +02:00
When both the key and the value are needed, it is more efficient to iterate the `entrySet()`, which will give access to both instead of
iterating over the `keySet()` and then getting the value.
If the `entrySet()` method is not iterated when both the key and value are needed, it can lead to unnecessary lookups. This is because each
lookup requires two operations: one to retrieve the key and another to retrieve the value. By iterating the `entrySet()` method, the
key-value pair can be retrieved in a single operation, which can improve performance.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
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
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
public void doSomethingWithMap(Map<String,Object> map) {
for (Map.Entry<String,Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Map.html[Oracle SE 20 - Map]
=== Articles & blog posts
* https://www.baeldung.com/java-map-entries-methods[Baeldung - Java Map methods]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Iterate over the "entrySet" instead of the "keySet".
endif::env-github,rspecator-view[]