Java Collections singletonMap()方法及实例
java.util.Collections 类的 singletonMap() 方法用于返回一个不可变的Map,只将指定的键映射到指定的值。返回的Map是可序列化的。
语法
public static Map singletonMap(K key, V value)
参数: 该方法需要以下参数作为参数
- key – 将被存储在返回的映射中的唯一键。
- value – 返回的Map将key映射到的值。
返回值: 该方法返回一个只包含指定键值映射的 不可变的Map
下面是说明singletonMap()方法的例子
例1 :
// 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);
}
}
}
输出
Singleton map is: {key=Value}
例2 :
// 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);
}
}
}
输出
Singleton map is: {100=true}