Prefer Map.of(..)

MSAL

Prefer Map.of(..) instead of using java.util.Map#put(..) in Java 10 or higher. Two input shapes are recognised:

  • Anonymous-class initialization (new HashMap<>() {{ put(k, v); ... }}), which is replaced wholesale with Map.of(k, v, ...) (or Map.ofEntries(...) past ten entries) — immutable result.
  • A new HashMap<>() declaration followed by a chain of target.put(k, v) statements, which is collapsed to new HashMap<>(Map.of(..)) (or new HashMap<>(Map.ofEntries(..))) — preserving the mutable HashMap.
org.openrewrite.java.migrate.util.UseMapOf
mod run . --recipe=org.openrewrite.java.migrate.util.UseMapOf

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