Horje
How to Create an Immutable TreeMap in Java and it's Benefits?

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

// Java program to create an immutable TreeMap 
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
  
public class ImmutableTreeMapExample 
{
    public static void main(String args[]) 
    {
        // Create a regular TreeMap
        TreeMap<String, Integer> regularTreeMap = new TreeMap<>();
        regularTreeMap.put("One", 1);
        regularTreeMap.put("Six", 6);
        regularTreeMap.put("Eight", 8);
  
        // Make it immutable using Collections.unmodifiableSortedMap
        SortedMap<String, Integer> immutableTreeMap = Collections.unmodifiableSortedMap(regularTreeMap);
  
        // Try to modify the immutable TreeMap (This will throw an exception)
        // immutableTreeMap.put("Two", 2);  
  
        // Print the immutable TreeMap
        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.



Reffered: https://www.geeksforgeeks.org


Java

Related
How to Execute a SQL Query Using JDBC? How to Execute a SQL Query Using JDBC?
How does HashTable Handle HashCode Distribution in Java? How does HashTable Handle HashCode Distribution in Java?
How to Create a LinkedHashSet with Custom Equality for Objects? How to Create a LinkedHashSet with Custom Equality for Objects?
How to Remove the Top Element From a PriorityQueue in Java? How to Remove the Top Element From a PriorityQueue in Java?
How to Handle an IOException in Java? How to Handle an IOException in Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13