Java Collections singletonMap()

singletonMap() 用于获取不可变的Map,仅将指定的键映射到指定的值。

1 语法

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

2 参数

key:这是key,将存储在返回的Map中。

value:这是value,返回的Map的key对应的值。

3 返回值

返回仅包含指定key-value对的映射的不可变Map。

4 Collections singletonMap()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singletonMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = Collections.singletonMap(1, 4);
        System.out.println("Output: "+map);
    }
}

输出结果为:

Output: {1=4}

5 Collections singletonMap()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singletonMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create singleton map
        Map<String,String> map = Collections.singletonMap("key","Value");
        System.out.println("Singleton map is: "+map);
    }
}

输出结果为:

Singleton map is: {key=Value}

6 Collections singletonMap()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singletonMap的例子
 */
import java.util.*;

public class Demo {

    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(key, value));
        sc.close();
    }
}

输出结果为:

Enter the key and value: 
666
Java
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.yiidian.Demo.main(Demo.java:17)

7 Collections singletonMap()示例4

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.singletonMap的例子
 */
import java.util.*;

public class Demo {

    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(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}

 

热门文章

优秀文章