Java Collections unmodifiableNavigableMap​() Method with Examples
Last Updated :
03 Jan, 2022
The unmodifiableMap() in java collections is used to get the unmodifiable view for the given map.
Syntax:
public static <Key,Value> Map<Key,Value> unmodifiableMap(Map<? extends Key, ? extends Key> map)
Parameters:
- Key is the key-value type
- Value is the value type
- map is the input map
Return: It will return the unmodifiable view for the given map.
Exceptions: This method will not throw any kind of exception.
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, String> data
= new HashMap<String, String>();
data.put( "1" , "manoj" );
data.put( "2" , "sai" );
data.put( "3" , "ramya" );
data.put( "4" , "sravan" );
System.out.println(data);
Map<String, String> final1
= Collections.unmodifiableMap(data);
System.out.println(final1);
}
}
|
Output
{1=manoj, 2=sai, 3=ramya, 4=sravan}
{1=manoj, 2=sai, 3=ramya, 4=sravan}
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<Integer, Integer> data
= new HashMap<Integer, Integer>();
data.put( 1 , 67 );
data.put( 2 , 34 );
System.out.println(data);
Map<Integer, Integer> final1
= Collections.unmodifiableMap(data);
System.out.println(final1);
}
}
|
Output
{1=67, 2=34}
{1=67, 2=34}
Example 3: It will throw an error when we add an element to a modifiable map.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<Integer, Integer> data
= new HashMap<Integer, Integer>();
data.put( 1 , 67 );
data.put( 2 , 34 );
System.out.println(data);
Map<Integer, Integer> final1
= Collections.unmodifiableMap(data);
final1.put( 3 , 45 );
System.out.println(final1);
}
}
|
Output:
{1=67, 2=34}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
at GFG.main(GFG.java:21)
Share your thoughts in the comments
Please Login to comment...