Prefer Set.of(..)

MSAL

Prefer Set.of(..) in Java 10 or higher. Two input shapes are recognised:

  • Anonymous-class initialization (new HashSet<>() {{ add("a"); add("b"); }}), which is replaced wholesale with Set.of("a", "b") (immutable result, matching the anonymous-class idiom's typical intent).
  • A new HashSet<>() declaration followed by a chain of target.add(..) statements, which is collapsed to new HashSet<>(Set.of(..)) (preserving the mutable HashSet).
org.openrewrite.java.migrate.util.UseSetOf
mod run . --recipe=org.openrewrite.java.migrate.util.UseSetOf

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