How to create a Map of more than 10 key-value pairs in Java
Nick Scialli
June 22, 2021
If you’re trying to create a Map
of more than 10 key/value pairs in Java, you may be having some trouble. For example, the following seems to work:
Map<String, String> items = Map.of(
"key-1", "value-1",
"key-2", "value-2",
"key-3", "value-3",
"key-4", "value-4",
"key-5", "value-5",
"key-6", "value-6",
"key-7", "value-7",
"key-8", "value-8",
"key-9", "value-9",
"key-10", "value-10");
But what if we want to add more key/value pairs to our map?
The problem
Adding just one more key/value pair to the Map
results in a compilation error:
Map<String, String> items = Map.of(
"key-1", "value-1",
"key-2", "value-2",
"key-3", "value-3",
"key-4", "value-4",
"key-5", "value-5",
"key-6", "value-6",
"key-7", "value-7",
"key-8", "value-8",
"key-9", "value-9",
"key-10", "value-10",
"key-11", "value-11");
You will get a cryptic error to the effect of:
no suitable method found for of(String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String)
The solution
For larger Maps, you can use the Map.ofEntries
method rather than Map.of
. You’ll additionally need to specify each key/value pair inside Map.entry
. Here’s an example of the aforementioned 11-pair Map
that will actually compile:
Map<String, String> items = Map.ofEntries(
Map.entry("key-1", "value-1"),
Map.entry("key-2", "value-2"),
Map.entry("key-3", "value-3"),
Map.entry("key-4", "value-4"),
Map.entry("key-5", "value-5"),
Map.entry("key-6", "value-6"),
Map.entry("key-7", "value-7"),
Map.entry("key-8", "value-8"),
Map.entry("key-9", "value-9"),
Map.entry("key-10", "value-10"),
Map.entry("key-11", "value-11"));
And there you have it—our code compiles and we can keep adding key/value pairs to our map!
Nick Scialli is a senior UI engineer at Microsoft.