Javatpoint Logo
Javatpoint Logo

Java Collections singletonMap() Method

The singletonMap() method of Java Collections class is used to get an immutable map, mapping only the specified key to the specified value.

Syntax

Following is the declaration of singletonMap() method:

Parameter

Parameter Description Required/Optional
key It is the key which will be stored in the returned map. Required
value It is the value to which the returned map maps the key. Required

Returns

The singletonMap() method returns an immutable map which contains only the specified key-value pair mapping.

Exceptions

NA

Compatibility Version

Java 1.3 and above

Example 1

Test it Now

Output:

Output: {1=4}

Example 2

Test it Now

Output:

Singleton map is: {key=Value}

Example 3

Test it Now

Output:

Enter the key and value: 
55
Java
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at myPackage.CollectionsSingletonMapExample3.main(CollectionsSingletonMapExample3.java:8)

Example 4

Test it Now

Output:

Before Singleton method-
Contents of the Map Elements
{1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday}

After singleton method-
Contents of the Map Elements
{1=Monday}





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA