Iterate a Map's entrySet() rather than its keySet()
org.openrewrite.staticanalysis.UseMapEntrySetIterationArtifactorg.openrewrite.recipe:rewrite-static-analysisA 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.
Usage
This recipe has no required configuration options. You’ll need the Moderne CLI configured before running the command below.
mod run . --recipe org.openrewrite.staticanalysis.UseMapEntrySetIterationIf the recipe isn’t available locally, install it with:
mod config recipes jar install org.openrewrite.recipe:rewrite-static-analysis:RELEASEData tables
Structured output this recipe can produce.
- Map `keySet()` iterationsLoops that iterate a map's `keySet()` and look the value up again with `get(key)`, and whether they were converted to `entrySet()` iteration.
org.openrewrite.staticanalysis.table.MapKeySetIterations - Source files that had resultsSource files that were modified by the recipe run.
org.openrewrite.table.SourcesFileResults - Source files that had search resultsSearch results that were found during the recipe run.
org.openrewrite.table.SearchResults - Source files that errored on a recipeThe details of all errors produced by a recipe run.
org.openrewrite.table.SourcesFileErrors - Recipe performanceStatistics used in analyzing the performance of recipes.
org.openrewrite.table.RecipeRunStats