Guava
ImmutableMap
Java
Java Collections
Programming Tips

How to initialize a Guava ImmutableMap?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Guava is a popular open-source set of libraries for Java, designed by Google. One of its notable features is immutable collections, which provide a way to create read-only collections that maintain high performance and thread safety. An ImmutableMap is one of these collections, and once constructed, it cannot be modified. This ensures that the map remains consistent, which is ideal for use cases where data integrity is essential. We'll explore how to initialize a Guava ImmutableMap using different methods.

Benefits of Using ImmutableMap

Before diving into the initialization, let's summarize the advantages of using an ImmutableMap:

  • Thread Safety: Unlike regular maps, immutable maps are inherently thread-safe because their state cannot be altered after construction.
  • Memory Optimization: Guava's immutable collections are optimized for memory usage, often requiring less overhead than their mutable counterparts.
  • Performance: The final nature of the map allows the compiler to make optimizations, leading to potential performance gains.
  • Defensive Copies: When returning a map to a caller, an ImmutableMap eliminates the need for creating defensive copies.

Initializing an ImmutableMap

Static Methods

The simplest way to create an ImmutableMap is by using its static methods. Guava provides methods like ImmutableMap.of() and ImmutableMap.builder() for straightforward initialization.

Using ImmutableMap.of()

ImmutableMap.of() is a convenient method for creating small maps. You can initialize it with up to 5 key-value pairs directly:

java
1import com.google.common.collect.ImmutableMap;
2
3public class Example {
4    public static void main(String[] args) {
5        // Creating an ImmutableMap with up to 5 entries
6        ImmutableMap<String, Integer> map = ImmutableMap.of(
7            "One", 1,
8            "Two", 2,
9            "Three", 3
10        );
11        
12        // Display the map
13        System.out.println(map);
14    }
15}

Using ImmutableMap.builder()

For larger maps or when readability is a concern, ImmutableMap.builder() can be used:

java
1import com.google.common.collect.ImmutableMap;
2
3public class Example {
4    public static void main(String[] args) {
5        // Using Builder to create a larger map
6        ImmutableMap<String, Integer> map = ImmutableMap.<String, Integer>builder()
7            .put("One", 1)
8            .put("Two", 2)
9            .put("Three", 3)
10            .put("Four", 4)
11            .put("Five", 5)
12            .build();
13        
14        // Display the map
15        System.out.println(map);
16    }
17}

Copying Existing Maps

If you already have a map and you want to create an immutable version, ImmutableMap.copyOf() is your best bet:

java
1import com.google.common.collect.ImmutableMap;
2
3import java.util.HashMap;
4import java.util.Map;
5
6public class Example {
7    public static void main(String[] args) {
8        // Initializing a regular HashMap
9        Map<String, Integer> mutableMap = new HashMap<>();
10        mutableMap.put("One", 1);
11        mutableMap.put("Two", 2);
12
13        // Creating an immutable copy
14        ImmutableMap<String, Integer> immutableMap = ImmutableMap.copyOf(mutableMap);
15
16        // Display the immutable map
17        System.out.println(immutableMap);
18    }
19}

Special Cases

Handling Collisions

ImmutableMap enforces that keys must be unique and will throw an exception if duplicate keys are added. It's crucial to ensure keys are distinct before initializing the map.

Null Values

Guava's ImmutableMap does not support null keys or values. Attempting to add a null will result in a NullPointerException.

Table of Methods

Here's a summary table of the methods used to initialize an ImmutableMap:

MethodDescriptionExample Usage
ImmutableMap.of()Quick initialization for up to 5 key-value pairs.ImmutableMap.of("key", value)
ImmutableMap.builder()Flexible, readable structure for larger maps.ImmutableMap.<K, V>builder().put(k, v).build()
ImmutableMap.copyOf()Creates an immutable map from an existing map.ImmutableMap.copyOf(existingMap)

Additional Topics

Best Practices

  • Use Builders for Readability: When initializing with more than a few entries, the builder pattern offers clarity and manageability.
  • Validate Input: Check for unique keys and non-null entries before applying these methods to prevent runtime exceptions.

Common Use Cases

  • Configuration Settings: Read-once application settings make ideal candidates for immutable maps.
  • Constant Data: Any dataset that should remain constant and requires concurrent access.

Conclusion

Understanding how to effectively use and initialize a Guava ImmutableMap allows for designing robust, high-performance Java applications. Leveraging its immutability properties ensures safer and more maintainable code, especially when dealing with shared data structures in multi-threaded environments.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.