Search code examples
javadictionarycollectionsguava

How to make an immutable map given a map using Guava?


Given a Map, how can I make an immutable map using Guava? I know one way through Collections.unmodifiableMap but is there any other way using Guava?

Map<String, String> realMap = Maps.newHashMap();
realMap.put("A", "B");

// any other alternative?
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

I am populating my realMap with some entries and then I need to make it Immutable so that no one can modify it. I am just trying to see if there is any alternative using Guava? I did some search but I cannot find it.


Solution

  • You're looking for ImmutableMap.copyOf():

    ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(realMap);
    

    Keep in mind that, as opposed to unmodifiableMap() which only creates a wrapper to its argument, this actually copies it to a new map. That can mean a slight performance hit, but it also means there's no possibility of the map being modified accidentally through realMap.