Thursday, September 25, 2025
HomeLanguagesJavaCollections singletonMap() method in Java with Examples

Collections singletonMap() method in Java with Examples

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




// Java program to demonstrate
// singletonMap() method
// for <String, String> Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton map
            // using singletonMap() method
            Map<String, String>
                map = Collections
                          .singletonMap("key", "Value");
 
            // printing the singletonMap
            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




// Java program to demonstrate
// singletonMap() method
// for <Integer, Boolean> Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // create singleton map
            // using singletonMap() method
            Map<Integer, Boolean>
                map = Collections
                          .singletonMap(100, true);
 
            // printing the singletonMap
            System.out.println("Singleton map is: "
                               + map);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output: 

Singleton map is: {100=true}

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6680 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS