Passing duplicate keys to Map.of() or Map.ofEntries(), or duplicate elements to Set.of(), throws an IllegalArgumentException at runtime during collection creation.

Unlike mutable collections such as HashMap (where duplicate keys overwrite previous entries) or HashSet (where duplicate elements are ignored), these static factory methods disallow duplicate keys and elements.

Why is this an issue?

Passing duplicate keys or duplicate elements to immutable collection factories is almost always a copy-paste error or a misunderstanding of the API contract. Because the factory methods validate their arguments at initialization time, duplicate entries cause an immediate runtime crash when the collection is constructed.

How to fix it

Review the arguments passed to the factory method:

Code examples

Noncompliant code example

import java.util.Map;
import java.util.Set;

class CollectionFactoryExamples {

  void createMap() {
    Map<String, Integer> config = Map.of(
      "timeout", 30,
      "retries", 3,
      "timeout", 60 // Noncompliant: "timeout" is duplicated
    );
  }

  void createEntriesMap() {
    Map<String, String> endpoints = Map.ofEntries(
      Map.entry("auth", "https://auth.example.com"),
      Map.entry("api", "https://api.example.com"),
      Map.entry("auth", "https://auth2.example.com") // Noncompliant: "auth" is duplicated
    );
  }

  void createSet() {
    Set<String> permissions = Set.of(
      "read",
      "write",
      "read" // Noncompliant: "read" is duplicated
    );
  }
}

Compliant solution

import java.util.Map;
import java.util.Set;

class CollectionFactoryExamples {

  void createMap() {
    Map<String, Integer> config = Map.of(
      "timeout", 30,
      "retries", 3,
      "port", 60
    );
  }

  void createEntriesMap() {
    Map<String, String> endpoints = Map.ofEntries(
      Map.entry("auth", "https://auth.example.com"),
      Map.entry("api", "https://api.example.com"),
      Map.entry("admin", "https://auth2.example.com")
    );
  }

  void createSet() {
    Set<String> permissions = Set.of(
      "read",
      "write",
      "execute"
    );
  }
}

Resources

Documentation

Related rules