Collections singletonMap() method in Java with Examples
Last Updated :
11 May, 2021
The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable.
Syntax:
public static Map singletonMap(K key, V value)
Parameters: This method takes the following parameters as a argument:
- key – the sole key to be stored in the returned map.
- value – the value to which the returned map maps key.
Return Value: This method returns an immutable map containing only the specified key-value mapping.
Below are the examples to illustrate the singletonMap() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Map<String, String>
map = Collections
.singletonMap( "key" , "Value" );
System.out.println( "Singleton map is: "
+ map);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Singleton map is: {key=Value}
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Map<Integer, Boolean>
map = Collections
.singletonMap( 100 , true );
System.out.println( "Singleton map is: "
+ map);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Singleton map is: {100=true}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...