Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map asUnmodifiable() method



Description

Groovy Map asUnmodifiable() method returns an unmodifiable copy of the current map.

Syntax

public Map asUnmodifiable()

Parameters

NA

Return Value

an unmodifiable copy of the map

Example - Getting Immutable Map of String and String

Following is an example of the usage of this method −

main.groovy

// define a map
def map = ["A" : "Apple", "B" : "Banana", "C": "Carrot"] 

def unmodifiableMap = map.asUnmodifiable()

try {
   // try to add a new value to the map
   unmodifiableMap.put("M","Mango")
}catch(UnsupportedOperationException e){
    println("Entry cannot be added.")
} 

try {
   // try to uodate value of the map
   unmodifiableMap.put("B","Mango")
}catch(UnsupportedOperationException e){
    println("Map cannot be modified.")
} 

Output

When we run the above program, we will get the following result −

Entry cannot be added.
Map cannot be modified.

Example - Getting immutable Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : 11, 2 : 12, 3: 6] 

def unmodifiableMap = map.asUnmodifiable()

try {
   // try to add a new value to the map
   unmodifiableMap.put(4,14)
}catch(UnsupportedOperationException e){
    println("Entry cannot be added.")
} 

try {
   // try to uodate value of the map
   unmodifiableMap.put(3,13)
}catch(UnsupportedOperationException e){
    println("Map cannot be modified.")
} 

Output

When we run the above program, we will get the following result −

Entry cannot be added.
Map cannot be modified.

Example - Getting immutable of Map of Integer and Object

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert")] 

def unmodifiableMap = map.asUnmodifiable()

try {
   // try to add a new value to the map
   unmodifiableMap.put(3,new Student(3, "Adam"))
}catch(UnsupportedOperationException e){
    println("Entry cannot be added.")
} 

try {
   // try to uodate value of the map
   unmodifiableMap.put(2,new Student(3, "Adam"))
}catch(UnsupportedOperationException e){
    println("Map cannot be modified.")
} 

class Student{
   int rollNo
   String name

   Student(int rollNo, String name){
      this.rollNo = rollNo
      this.name = name
   }

   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name)
   }
   
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]"
   }
}

Output

When we run the above program, we will get the following result −

Entry cannot be added.
Map cannot be modified.
groovy_maps.htm
Advertisements