Reputation: 47
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");
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?
Upvotes: 1
Views: 11513
Reputation: 718906
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:
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 ...
Upvotes: 3