In Java, the Map.of()
factory method can be used to create an unmodifiable map of specified key-value pairs. This method is available in Java 9 and later versions.
Creating a map is a bit more complicated than creating lists or sets. Because we need to provide keys and values when creating a map. When using the Map.of()
factory method we set the content of the map by alternating between the keys and values of the map.
Consider the following example:
package org.kodejava.util;
import java.util.Map;
public class MapOfExample {
public static void main(String[] args) {
Map<String, Integer> map = Map.of("John", 25, "Mary", 30, "Alice", 27, "Rosa", 22);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Output:
Rosa : 22
Mary : 30
John : 25
Alice : 27
In the example above, the Map.of("John", 25, "Mary", 30, "Alice", 27, "Rosa", 22)
statement creates an unmodifiable map with three key-value pairs. After the map is created, any attempt to modify the map (add, update or remove elements) will throw an UnsupportedOperationException
.
Note that Map.of()
doesn’t accept null
keys or values. If a null
key or value is provided, then a NullPointerException
is thrown. Besides, if duplicate keys are provided, an IllegalArgumentException
is thrown.
The Map.of()
method is overloaded to accept up to 10 key-value pairs. If there are more than 10 pairs, you can use Map.ofEntries()
factory method to create a map. This is how we use it:
Map<String, Integer> map = Map.ofEntries(
Map.entry("John", 25),
Map.entry("Mary", 30),
Map.entry("Alice", 27),
Map.entry("Bob", 32),
// ...
);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
The Map.entry()
is another factory method provided to create Map.Entry
object.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024