Converting immutable to mutable map java

I have an immutable map that I get from the method in another part. And when processing I want to delete a key from it and then use it further, the key is always on the map.

    ImmutableMap<String, Object> immutableMap =  doSomethingAndGetImmutableMap();
    
    // convert to mutable
    Map<String, Object>  newMutableMap =  ??

    newMutableMap.remove("pin");
   
    // other code

Is there any built-in method to do convert immutable to mutable map java? I saw there are several ways to do the opposite but not from immutable to mutable map.

I used Maps.newHashMap but is it the best and the most efficient way?


Solution 1:

You can simply create a new HashMap from the existing Map using the copy constructor.

 HashMap<String, Object> = new HashMap<>(immutableMap);

Note that this is a brand new object. There isn't a way to make an immutable map mutable. That would be breaking abstraction. I guess conceptually you could design mutable wrapper for an immutable map that stored the changes in a second (private) map structure. But Guava doesn't appear to support that.


Is this or Maps.newHashMap more performant?

Guava Maps.newHashMap(map) simply returns new HashMap<>(map). That call will be inlined by the JIT compile, so there should be zero performance difference on a modern JVM once the code has been JIT compiled.

You are almost certainly wasting your time micro-optimizing this kind of stuff:

  • You should FIRST design and write the application code and get it to work.
  • THEN you benchmark it.
  • THEN you decide from the benchmark results if the application needs optimizing at all.
  • THEN you profile it to determine where the performance hotspots are.
  • THEN you optimize the performance hotspots.

Unless there is something really weird, following the above procedure would have lead to you not wasting your time asking this question. To paraphrase1 Donald Knuth:

"Premature optimization is the root of all evil".


1 ... and oversimplify / take out of context ...