Skip to main content

How to Create a Map in Java with Map.of

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Map.of("free", 10, "pro", 500) creates a Java map from keys and values written one after the other, in one line. The map can't be changed afterwards, doesn't keep the order you wrote, and refuses a key given twice with an IllegalArgumentException.

Syntax​

Syntax
Map<KeyType, ValueType> name = Map.of(key1, value1, key2, value2, ...);
PartWhat it does
Map.of(...)Creates an unmodifiable map from up to ten key-value pairs.
key1, value1, ...Each key followed by its value. No key can appear twice, and no key or value can be null.
KeyType, ValueTypeThe types of the keys and of the values, such as String and Integer.
nameThe variable's name.

The Map documentation: "The Map.of, Map.ofEntries, and Map.copyOf static factory methods provide a convenient way to create unmodifiable maps." Among their characteristics: "They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException." And: "The iteration order of mappings is unspecified and is subject to change."

The Example​

The example maps two plan names to their limits, then prints the map, the value for pro and the number of entries. A changed version then gives the key pro twice.

Prerequisites​

  • A JDK 11 or later, which can run a single .java file directly. This guide uses OpenJDK 25.0.5.1.

Step 1: Write the Code​

Create a file named Main.java:

Main.java, which creates a map of String to Integer with Map.of from free 10 and pro 500, then prints the map, the value for pro and the map's size.

Main.java
import java.util.Map;

public class Main {

public static void main(String[] args) {
Map<String, Integer> limits = Map.of("free", 10, "pro", 500);

System.out.println(limits);
System.out.println(limits.get("pro"));
System.out.println(limits.size());
}
}

Step 2: Run It​

Terminal
java Main.java
Output
{pro=500, free=10}
500
2

java Main.java compiles the file in memory and runs it. The command is the same in zsh, bash and PowerShell. Your map may print in the other order, for the reason below.

Step 3: Give a Key Twice​

Replace Main.java with a version that gives pro a second value:

Main.java
import java.util.Map;

public class Main {

public static void main(String[] args) {
Map<String, Integer> limits = Map.of("free", 10, "pro", 500, "pro", 900);

System.out.println(limits);
}
}
Terminal
java Main.java
Output
Exception in thread "main" java.lang.IllegalArgumentException: duplicate key: pro
at java.base/java.util.ImmutableCollections$MapN.<init>(ImmutableCollections.java:1440)
at java.base/java.util.Map.of(Map.java:1406)
at Main.main(Main.java:6)

A zsh terminal where java Main.java prints the map with pro=500 and free=10 in braces, then 500 and 2, and then, for the changed file, stops with java.lang.IllegalArgumentException: duplicate key: pro.

What Happened​

  • The map printed as {pro=500, free=10}: each key, an equals sign and its value, between braces. That's not the order of the code. The order of a Map.of map can even change from one run to the next: a map of four plans printed {basic=50, team=2000, pro=500, free=10} twice, and then {free=10, pro=500, team=2000, basic=50}.
  • limits.get("pro") returned 500, the value stored under that key.
  • limits.size() returned 2, one for each key.
  • The changed version stopped with IllegalArgumentException: duplicate key: pro before it printed anything, because pro was given twice.

Common Mistakes​

MistakeWhat happensDo this instead
Expecting the entries in the order you wrote themThe map prints in another order, which can change between runsUse a LinkedHashMap, which keeps the order of put
A null key or valueNullPointerException, thrown from Objects.requireNonNull inside Map.ofLeave that pair out
Calling put on a Map.of mapUnsupportedOperationExceptionCopy it into a map that can change: new HashMap<>(Map.of(...))
More than ten pairs in Map.oferror: no suitable method found for of(String,int,...)Use Map.ofEntries(Map.entry("free", 10), ...), which takes any number

Troubleshooting​

SymptomLikely causeFix
java.lang.IllegalArgumentException: duplicate key: proThe same key is given twiceRemove one of them
java.lang.NullPointerException at java.util.Objects.requireNonNull, with java.util.Map.of further down the stack traceA key or a value is nullLeave that pair out
java.lang.UnsupportedOperationException at java.util.ImmutableCollections.uoeThe code changes a map made with Map.ofCopy it into a HashMap first
error: no suitable method found for of(...)Map.of was given eleven or more pairsUse Map.ofEntries

FAQ​

How many pairs can Map.of take?​

Ten. The largest version of Map.of "Returns an unmodifiable map containing ten mappings." Map.ofEntries has no such limit: given eleven entries made with Map.entry, it made a map whose size() was 11.

Can the values have different types?​

Yes, when the value type is Object. A Map<String, Object> made with Map.of held the String pro and the Integer 500 side by side.

How do I keep the entries in the order I added them?​

Use a LinkedHashMap and add the entries with put. Its documentation says its order "is normally the order in which keys were inserted into the map (insertion-order)", and four plans put into one printed {free=10, pro=500, team=2000, basic=50} on every run.

Conclusion​

Map.of makes a small map in one line from up to ten key-value pairs. The map can't change, can't hold null, refuses duplicate keys, and promises no order, so use a LinkedHashMap when the order matters and a HashMap copy when the code needs to change it.

Additional Resources​