← All recipes
Moderne licensed

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

Recipe IDorg.openrewrite.staticanalysis.UseMapEntrySetIterationArtifactorg.openrewrite.recipe:rewrite-static-analysis

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.

Single recipeRSPEC-S2864MSAL

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.UseMapEntrySetIteration

If the recipe isn’t available locally, install it with:

mod config recipes jar install org.openrewrite.recipe:rewrite-static-analysis:RELEASE

Data 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