Collections.singletonMap() method in Java and its examples

In Java, the Collections utility class provides a variety of methods for manipulating collections. Among them, the singletonMap() method is used to create an immutable map containing only one key-value pair (that is, the implementation class of the Map interface). That is to say, the map has only one key and corresponding value.

Definition and syntax of singletonMap() method

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

In the syntax of the singletonMap() method, two parameters can be passed, one is the key and the other is the value. The parameter type can be any type. The previous K and V are the type parameters of Java generics.

The return value is a Map instance with size 1 and containing the specified key and value.

import java.util.Collections;
import java.util.Map;

public class SingletonMapDemo {

   public static void main(String[] args) {
      // 创建一个只包含一个键值对的map
      Map<String, String> map = Collections.singletonMap("key1", "value1");

      // 输出map中的元素
      System.out.println(map); // {key1=value1}

      // 尝试修改map
      // map.put("key2", "value2");  // 运行时抛出java.lang.UnsupportedOperationException异常
   }
}

The singletonMap method is a quick way to create an immutable map containing only one element. It will return a Map instance with size 1 and containing the specified key and value. Using the singletonMap method is the fastest way to create a map and is suitable for scenes that only contain one element. Because the instance it returns is immutable, it is thread-safe. However, adding, deleting, or modifying key-value pairs is not supported. If you need to operate on the map, you can use other Map implementation classes.

Guess you like

Origin blog.csdn.net/tck001221/article/details/132269217