Java中的集合 singletonMap() 方法和示例
Java.util.Collections类的singletonMap()方法用于返回一个不可变映射,仅将指定的键映射到指定的值。返回的地图是可序列化的。
句法:
public static Map singletonMap(K key, V value)
参数:此方法将以下参数作为参数:
- key --要存储在返回的映射中的唯一键。
- value --返回的映射映射键的值。
返回值:该方法返回一个不可变的映射,只包含指定的键值映射。
以下是说明singletonMap()方法的示例
示例 1:
Java
// Java program to demonstrate
// singletonMap() method
// for Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// create singleton map
// using singletonMap() method
Map
map = Collections
.singletonMap("key", "Value");
// printing the singletonMap
System.out.println("Singleton map is: "
+ map);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Java
// Java program to demonstrate
// singletonMap() method
// for Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// create singleton map
// using singletonMap() method
Map
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: {key=Value}
示例 2:
Java
// Java program to demonstrate
// singletonMap() method
// for Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// create singleton map
// using singletonMap() method
Map
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}