Search code examples
javacollectionsdictionaryunmodifiable

How do I make a Map<String, List<String> unmodifiable?


The java.util.Collections class allows me to make collection instances unmodifiable. The following method

protected Map<String, List<String>> getCacheData() {
    return Collections.unmodifiableMap(tableColumnCache);
}

returns an umodifiable Map, so that an UnsupportedOperationException is caused by attempting to alter the map instance.

@Test(expected = UnsupportedOperationException.class)
public void checkGetCacheData_Unmodifiable() {
    Map<String, List<String>> cacheData = cache.getCacheData();
    cacheData.remove("SomeItem");
}

Unfortunately all List<String> childs aren't unmodifiable. So I want to know whether there is a way to enforce the unmofiable behavior for the child values List<String> too?

Of course, alternatively I can iterate through the maps key value pairs, make the lists unmodifiable and reassemble the map.


Solution

  • You need an ImmutableMap full of ImmutableList instances. Use Guava to preserve your sanity.

    To start off, create ImmutableList instances that you require:

    ImmutableList<String> list1 = ImmutableList.of(string1, string2, etc);
    ImmutableList<String> list2 = ImmutableList.of(string1, string2, etc);
    

    Then create your ImmutableMap:

    ImmutableMap<String,List<String>> map = ImmutableMap.of("list1", list1, "list2", list2);
    

    There are numerous ways to instantiate your immutable lists and maps, including builder patterns. Check out the JavaDocs for ImmutableList and ImmutableMap for more details.