Guava ImmutableMap of() and ofEntries() method in Java
In this post, we will show you how to use the ImmutableMap.of() and ImmutableMap.ofEntries() methods in Java, and explain why they are useful and how they work. We will also compare them with other ways of creating immutable maps in Java, and highlight some of their advantages.
The ImmutableMap class represents an immutable map that preserves the insertion order of its entries. It provides two static methods called of() and ofEntries(), which return an immutable map containing the given entries in order.
1. Overview of ImmutableMap.of() and ImmutableMap.ofEntries() methods
The ImmutableMap.of() method returns an immutable map containing the fixed number of key-value pairs in order. To use the ImmutableMap.of() method, you need to provide the key-value pairs that you want to include in the immutable map. The keys and values can be any objects that are not null. The order of the arguments determines the order of the entries in the returned map. The method has the following signature:
|
1 |
public static <K,V> ImmutableMap<K,V> of(K k1, V v1, K k2, V v2, ... K k5, V v5) |
The method takes up to 10 parameters, which are alternating keys and values. It returns an immutable map that contains the given entries in order. For example:
|
1 2 3 4 5 6 7 8 9 10 11 |
import com.google.common.collect.ImmutableMap; class Main { public static void main(String[] args) { ImmutableMap<String, String> map = ImmutableMap.of("USA", "Washington D.C.", "UK", "London", "France", "Paris"); // {USA=Washington D.C., UK=London, France=Paris} System.out.println(map); } } |
To create an immutable map with an unknown number of key-value pairs, you can use the ImmutableMap.ofEntries() method. It returns an immutable map containing the given entries in order. The method has the following signature:
|
1 |
public static <K,V> ImmutableMap<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries) |
This method works for any number of entries. The entries can be created using the Map.entry() method or the AbstractMap.SimpleEntry class. For example, suppose you want to create an ImmutableMap with three entries:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import com.google.common.collect.ImmutableMap; import java.util.Map; class Main { public static void main(String[] args) { ImmutableMap<String, String> map = ImmutableMap.ofEntries( Map.entry("USA", "Washington D.C."), Map.entry("UK", "London"), Map.entry("France", "Paris") ); System.out.println(map); // {USA=Washington D.C., UK=London, France=Paris} } } |
Both methods return an instance of ImmutableMap that cannot be modified directly or indirectly. Any attempt to do so will result in an UnsupportedOperationException. Also if you provide duplicate keys, both methods will throw an IllegalArgumentException at runtime. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.collect.ImmutableMap; class Main { public static void main(String[] args) { // This will throw an exception ImmutableMap<String, String> map = ImmutableMap.of( "USA", "Washington D.C.", "UK", "London", "USA", "New York" ); // Exception in thread "main" java.lang.IllegalArgumentException: // Multiple entries with same key: USA=New York and USA=Washington D.C. } } |
2. Comparison with other ways of creating Immutable Maps in Java
There are other ways of creating immutable maps in Java, such as using Collections.unmodifiableMap(), Map.of(), or ImmutableMap.copyOf(). How do they compare with using ImmutableMap.of() and ofEntries()? Here are some differences:
Collections.unmodifiableMap()returns a view of a map that cannot be modified, but does not guarantee immutability of the underlying map. If the underlying map is modified, the view will reflect the changes. It also does not preserve the insertion order of the entries.Map.of()returns an immutable map that contains a fixed number of key-value pairs. It preserves the order of the entries, but does not allownullvalues. It does not accept streams or entries as input, and requires you to specify each key-value pair as a separate argument.ImmutableMap.copyOf()returns an immutable map that contains all the entries from an iterable or a stream. It preserves the order of the entries and creates a copy of the input map.
3. Why use ImmutableMap.of() and ImmutableMap.ofEntries() methods
Here are some reasons why you should use the ImmutableMap.of() and ImmutableMap.ofEntries() methods instead of other ways of creating immutable maps in Java.
- They are concise and expressive. You can create an immutable map with a few entries in one line of code, without having to create a mutable map first and then wrap it with
Collections.unmodifiableMap()orImmutableMap.copyOf(). - They are efficient and optimized. They avoid unnecessary copying and allocation of intermediate maps, and use a smart algorithm to choose the optimal implementation of
ImmutableMapbased on the number and characteristics of the entries. - They are consistent and reliable. They always return an
ImmutableMapthat preserves the insertion order of the entries, regardless of the source or the parallelism of the stream. They also throw an exception if duplicate keys are provided, instead of silently ignoring them or overwriting them.
That’s all about Guava ImmutableMap.of() and ImmutableMap.ofEntries() methods in Java. For more information about these methods, you can check out the Guava official documentation or its GitHub repository.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)