![]() |
VOOZH | about |
Advantages of ImmutableMap
Note that it is an immutable collection, not collection of immutable objects, so the objects inside it can be modified.
Class Declaration:
@GwtCompatible(serializable=true, emulated=true) public abstract class ImmutableMap extends Object implements Map, Serializable
Class hierarchy:
java.lang.Object ↳ com.google.common.collect.ImmutableMap
Creating ImmutableMap ImmutableMap can be created by various methods. These include:
{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
Try to change ImmutableMap As mentioned earlier, the below program will throw UnsupportedOperationException.
Output :
Exception in thread "main" java.lang.UnsupportedOperationException at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218) at ImmutableListDemo.main(Main.java:16)
How is it different from Collections.unmodifiableMap()? Collections.unmodifiableMap creates a wrapper around the same existing Map such that the wrapper cannot be used to modify it. However we can still change original Map.
Output:
{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}
If we create an ImmutableMap from an existing Map and change the existing Map, the ImmutableMap does not change because a copy is created.
Output :
{1=Geeks, 2=For, 3=Geeks}1) Using Collections.singletonMap()
Description: The Collections.singletonMap() method returns an immutable map containing only one mapping. It is used to create a map with a single key-value pair.
Syntax:
Collections.singletonMap(key, value)
Example:
{gfg=25}Note: This will throw an UnsupportedOperationException because the map is immutable