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.
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.
Review the arguments passed to the factory method:
Map.of() and Map.ofEntries(), remove the redundant key-value pair or replace the duplicate key with the intended
distinct key.Set.of(), remove the duplicated element or replace it with the intended distinct element.
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
);
}
}
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"
);
}
}