Iterate a Map's entrySet() rather than its keySet()

MSAL

A loop over map.keySet() that calls map.get(key) hashes and probes the map again for every element, which on a TreeMap costs an extra O(log n) lookup per iteration. Iterating map.entrySet() instead hands the loop both the key and the value. The loop is only rewritten when:

  • The map is a simple reference that is neither modified nor reassigned inside the loop.
  • get is called only with the loop variable.
  • The loop variable is neither reassigned nor captured by a lambda or anonymous class.

Every candidate loop, converted or not, is recorded in a data table along with the reason it was left alone.

org.openrewrite.staticanalysis.UseMapEntrySetIteration
mod run . --recipe=org.openrewrite.staticanalysis.UseMapEntrySetIteration

Install it once from Recipe actions, then run it on every repository under the current directory. New to the Moderne CLI? Set it up.