ImmutableMap Notes By ShariqSP
Understanding ImmutableMap.of and Map.of
ImmutableMap.of is a method provided by the ImmutableMap
class in the Guava library, developed by Google. This method is used to create an immutable map with a fixed number of key-value pairs. An immutable map is a map whose entries cannot be modified, added, or removed after it has been created. This ensures thread safety and eliminates accidental modifications, making it ideal for scenarios where data integrity and consistency are critical.
Usage of ImmutableMap.of
The method ImmutableMap.of
is overloaded to allow creating maps with up to five key-value pairs directly. For example:
// Creating an immutable map with ImmutableMap.of
import com.google.common.collect.ImmutableMap;
ImmutableMap map = ImmutableMap.of(
"key1", "value1",
"key2", "value2",
"key3", "value3"
);
System.out.println(map);
If you need more than five key-value pairs, use the ImmutableMap.builder()
method to construct the map dynamically.
Advantages of ImmutableMap
- Ensures data integrity by preventing modification.
- Provides thread safety, as the structure is inherently immutable.
- Enhances performance by avoiding runtime checks for modifications.
Map.of
Map.of is a similar utility introduced in Java 9 as part of the java.util
package. It allows for the creation of small, unmodifiable maps in a concise manner. This method is also overloaded to handle up to ten key-value pairs.
Usage of Map.of
Here is an example of how to use Map.of
:
// Creating an unmodifiable map with Map.of
import java.util.Map;
Map map = Map.of(
"key1", "value1",
"key2", "value2",
"key3", "value3"
);
System.out.println(map);
To create a larger map, you can use Map.ofEntries
or consider using the Map
interface's Collectors.toMap
in conjunction with streams for more complex scenarios.
Key Differences
- Library:
ImmutableMap.of
is part of the Guava library, whileMap.of
is part of Java's standard library. - Compatibility:
ImmutableMap.of
can be used with older versions of Java (with Guava dependency), whileMap.of
requires Java 9 or higher. - Customization:
ImmutableMap.builder()
allows more advanced customization compared toMap.of
.
Both methods are efficient ways to create small, fixed maps and enhance code readability by providing a concise syntax.