How to Create an Immutable TreeMap in Java and it’s Benefits?
Last Updated :
16 Feb, 2024
A TreeMap is a component of the Java Collections Framework in Java. A TreeMap is immutable which means it cannot be changed once it has been created. This implies that you are unable to add, delete, or change any items after the TreeMap has been created.
In this article, we will learn how to create an immutable TreeMap in Java.
Syntax of Creating a TreeMap:
TreeMap<Integer, String> tp = new TreeMap<Integer, String>();
Program to Create an Immutable TreeMap in Java
Below is the implementation of Creating an Immutable TreeMap:
Java
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class ImmutableTreeMapExample
{
public static void main(String args[])
{
TreeMap<String, Integer> regularTreeMap = new TreeMap<>();
regularTreeMap.put( "One" , 1 );
regularTreeMap.put( "Six" , 6 );
regularTreeMap.put( "Eight" , 8 );
SortedMap<String, Integer> immutableTreeMap = Collections.unmodifiableSortedMap(regularTreeMap);
System.out.println( "Immutable TreeMap: " + immutableTreeMap);
}
}
|
Output
Immutable TreeMap: {Five=5, One=1, Three=3}
Explanation of the above Program:
- We have created a regular
TreeMap
called regularTreeMap
.
- We made the
regularTreeMap
immutable by covering it with Collections.unmodifiableSortedMap
. This returns an unmodifiable view of the specified sorted map.
- Then we tried to modify the immutable
TreeMap
by adding a new key-value pair, but it will throw an UnsupportedOperationException
since the map is immutable.
- At last, it prints the immutable
TreeMap
.
Benefits of Immutability in Java
- Thread Safety: Since immutable objects’ states cannot be changed, they are by nature thread-safe. As a result, they may be used in concurrent situations and no longer need locks.
- Code Simplified: Code that is easier to read and maintain is encouraged by immutability. An immutable object has fewer opportunities for problems relating to state updates since its state cannot change.
- Predictable Behavior: Your applications will behave more predictably when you use immutable objects since you can count on their state to remain constant.
- Easier Testing: Since immutable objects don’t change throughout the course of their lives, testing is simpler with them. In addition to ensuring consistent behavior, this streamlines unit testing.
- Sharing and Reusability: There is no chance of inadvertent alterations when immutable objects are easily shared across other components. This encourages functional programming and improves code reuse.
Share your thoughts in the comments
Please Login to comment...