Java Collections singletonMap()
Java Collections 类的
singletonMap()方法用于获取不可变的映射,仅映射指定的键
语法
以下是
singletonMap()方法的声明:
public static <K,V> Map<K,V> singletonMap(K key, V value)
参数
参数 |
说明 |
必需/可选 |
key |
这是密钥,它将存储在返回的地图中。 |
必需 |
value |
它是返回的映射将键映射到的值。 |
必需 |
返回
singletonMap()方法返回一个不可变的映射,其中仅包含指定的键值对映射。
异常
NA
兼容版本
Java 1.3及更高版本
示例1
import java.util.*;
public class CollectionsSingletonMapExample1 {
public static void main(String[] args) {
Map<Integer, Integer> map = Collections.singletonMap</span>(1, 4);
System.out.println("Output: "+map);
}
}
输出:
示例2
import java.util.*;
public class CollectionsSingletonMapExample2 {
public static void main(String[] args) {
//Create singleton map
Map<String,String> map = Collections.singletonMap</span>("key","Value");
System.out.println("Singleton map is: "+map);
}
}
输出:
Singleton map is: {key=Value}
示例3
import java.util.*;
public class CollectionsSingletonMapExample3 {
public static void main(String[] args) {
System.out.println("Enter the key and value: ");
Scanner sc = new Scanner(System.in);
int key = sc.nextInt();
int value = sc.nextInt();
System.out.println("Output: "+Collections.singletonMap</span>(key, value));
sc.close();
}
}
输出:
Enter the key and value:
55
Java
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at myPackage.CollectionsSingletonMapExample3.main(CollectionsSingletonMapExample3.java:8)
示例4
package myPackage;
import java.util.*;
public class CollectionsSingletonMapExample4 {
public static void main(String[] args) {
Map<Integer, String> m1 = new HashMap<Integer, String>();
m1.put(1, "Sunday");
m1.put(2, "Monday");
m1.put(3, "Tuesday");
m1.put(4, "Wednesday");
System.out.println("Before Singleton method-");
System.out.println("Contents of the Map Elements");
System.out.print( m1);
System.out.println("\n");
System.out.println("After singleton method-");
m1 = Collections.singletonMap</span>(1, "Monday");
System.out.println("Contents of the Map Elements");
System.out.println(m1);
}
}
输出:
Before Singleton method-
Contents of the Map Elements
{1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday}
After singleton method-
Contents of the Map Elements
{1=Monday}