Java Utility Library

Java Collections - singletonMap() Method



The java.util.Collections.singletonMap() method returns an immutable map, mapping only the specified key to the specified value. The returned map is serializable.

Syntax

public static <K,V> Map<K,V> singletonMap(K key, 
                                          V value)

Here, K and V are the type of key and value respectively maintained by the map.


Parameters

key Specify the class of the map keys.
value Specify the class of the map values.

Return Value

Returns an immutable map containing only the specified key-value mapping.

Exception

NA.

Example:

In the example below, the java.util.Collections.singletonMap() method returns an immutable map containing only the specified key-value mapping.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a map
    Map<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating MyMap
    MyMap.put(102, "John");
    MyMap.put(101, "Marry");
    MyMap.put(103, "Kim");

    //printing the map
    System.out.println("MyMap contains: " + MyMap);

    //creating singleton map
    MyMap = Collections.singletonMap(100, "Hundred");

    //printing the map
    System.out.println("MyMap contains: " + MyMap);
  }
}

The output of the above code will be:

MyMap contains: {101=Marry, 102=John, 103=Kim}
MyMap contains: {100=Hundred}

❮ Java.util - Collections