Initialize Map in Java using Guava Library
The Google Guava libraries provide a rich set of utilities for creating mutable and immutable Maps. This article will discuss various methods to initialize a map using Guava in Java.
1. Mutable Map
Maps.newHashMap() creates a mutable HashMap instance with the same mappings as the specified map. We should use this method if you need to add or remove entries later.
|
1 |
Map<String, String> mutableMap = Maps.newHashMap(map); |
If no argument is passed to Maps.newHashMap(), an empty HashMap instance is created.
|
1 |
Map<String, String> emptyMap = Maps.newHashMap(); |
This method is deprecated in Java 7 and above.
2. Immutable Maps
Guava provides several simple, easy-to-use immutable implementations of Map. Guava’s immutable list does not allow any null key or value (why?). It will throw a NullPointerException if any key or value in the map is null and an UnsupportedOperationException if any modification operation is performed on it. Since the returned map is immutable, any change in the underlying mutable map will not be visible in the unmodifiable map.
⮚ ImmutableMap.copyOf() method
ImmutableMap.copyOf returns an immutable map containing the same entries as the specified map. Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. If the map somehow contains entries with duplicate keys (for example, if it is a SortedMap whose comparator is not consistent with equals), the results of this method are undefined.
|
1 |
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(map); |
⮚ ImmutableMap.Builder
Guava also provides a builder for creating immutable map instance using Builder’s putAll() method. putAll() associates all the given map’s keys and values in the built map.
|
1 2 3 4 |
ImmutableMap<String, String> immutableMap = new ImmutableMap .Builder<String, String>() .putAll(map) .build(); |
⮚ ImmutableMap.of() method
Guava’s ImmutableMap.of() returns an immutable map containing the given entries in order. It will throw an IllegalArgumentException if duplicate keys are provided.
|
1 2 3 4 5 6 |
Map.of() // creates an empty map Map.of(k1, v1) // creates a singleton map Map.of(k1, v1, k2, v2) Map.of(k1, v1, k2, v2, k3, v3) Map.of(k1, v1, k2, v2, k3, v3, k4, v4) Map.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5) |
For example,
|
1 2 |
Map<String, String> immutableMap = ImmutableMap.of("United States", "Washington D.C.", "United Kingdom", "London"); |
The above code will create a map {United States=Washington D.C., United Kingdom=London}
This method supports up to 5 key/value pairs. To create a map with more than 5 entries, we can use Builder’s put() method, which takes key-value pairs instead of a map. put() associates key with value in the built map. Duplicate keys are not allowed and will cause build() to fail.
|
1 2 3 4 |
ImmutableMap<String, String> immutableMap = ImmutableMap.builder<String, String>() .put("k1", "v1") .put("k2", "v2") .build(); |
3. Immutable Sorted Maps
A SortedMap provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys or by a provided Comparator.
Guava’s ImmutableSortedMap throws:
NullPointerExceptionif any key or value in the map is null.UnsupportedOperationExceptionif any modify operation is performed on it (Any change in the underlying mutable map will not be visible in the unmodifiable map).IllegalArgumentExceptionif any two keys are equal according to their natural ordering or provided comparator.
⮚ ImmutableSortedMap.copyOf() method
It has many variations:
1. Returns an immutable map containing the same entries as the provided sorted map, with the same ordering.
|
1 |
ImmutableSortedMap<String, String> immutableMap = ImmutableSortedMap.copyOf(sortedmap); |
2. Returns an immutable map containing the same entries as the map, sorted by the natural ordering of the keys.
|
1 |
ImmutableSortedMap<String, String> immutableMap = ImmutableSortedMap.copyOf(map); |
3. Returns an immutable map containing the same entries as the map, with keys sorted by the provided comparator.
|
1 2 |
ImmutableSortedMap<String, String> immutableMap = ImmutableSortedMap.copyOf(map, Comparator.<String>reverseOrder()) |
⮚ ImmutableSortedMap.Builder
Guava also provides a builder for creating immutable sorted map instances whose keys are ordered by the provided comparator.
|
1 2 3 4 |
ImmutableSortedMap<String, String> immutableMap = new ImmutableSortedMap .Builder<String, String>(Ordering.natural()) .putAll(map) .build(); |
⮚ ImmutableSortedMap.of() method
Guava’s ImmutableSortedMap.of() returns an immutable sorted map containing the given entries, sorted by the natural ordering of their keys. Its prototype is similar to ImmutableMap.of()
4. Using Multimap
Multimap is a collection that maps keys to values, similar to a map, but each key may be associated with multiple values. We can use Multimap to associate each key with multiple values. There are many implementations of Multimap. The most commonly used ones are ArrayListMultimap that internally uses an ArrayList, and HashMultimap uses hash tables to store the values for a given key.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; class Main { // `MultiMap` in Java public static void main(String[] args) { Multimap<String, String> multiMap = ArrayListMultimap.create(); multiMap.put("USA", "New York City"); multiMap.put("USA", "Los Angeles"); multiMap.put("USA", "Seattle"); multiMap.put("Asia", "Tokyo"); multiMap.put("Asia", "Beijing"); multiMap.put("Asia", "Mumbai"); // prints {USA=[New York City, Los Angeles, Seattle], // Asia=[Tokyo, Beijing, Mumbai]} System.out.println(multiMap); } } |
That’s all about initializing Map in Java using Guava Library.
Related Posts:
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 :)