Java Collections singletonMap()方法与示例

集合类singletonMap()方法 (Collections Class singletonMap() method)

  • singletonMap() method is available in java.util package.

    singletonMap()方法在java.util包中可用。

  • singletonMap() method is used to return an immutable map (i.e. immutable map is a map that contains the given key & value only & mapping would be based on the given key to the given value.

    singletonMap()方法用于返回不可变的映射(即,不可变的映射是仅包含给定键和值的映射,并且映射将基于给定键到给定值。

  • singletonMap() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.

    singletonMap()方法是静态方法,因此可以使用类名进行访问,如果尝试使用类对象访问该方法,则不会收到错误。

  • singletonMap() method does not throw an exception at the time of returning an immutable map.

    在返回不可变地图时, singletonMap()方法不会引发异常。

Syntax:

句法:

    public static Map singletonMap(Type key_ele, Type val_ele);

Parameter(s):

参数:

  • Type key_ele – represents the key to be saved in the returned map.

    key_ele类型 –表示要保存在返回的映射中的密钥。

  • Type val_ele – represents the value(val) associated with the key_ele.

    类型val_ele –表示与key_ele关联的value( val )。

Return value:

返回值:

The return type of this method is Map, it returns an immutable map that contains the given key-value pairs only of the map.

此方法的返回类型为Map ,它返回一个不可变的映射,其中仅包含该映射的给定键值对。

Example:

例:

// Java program is to demonstrate the example of
// singletonMap(Type key_ele, Type val_ele)
// method of Collections

import java.util.*;

public class SingletonMapOfCollections {
    public static void main(String args[]) {
        // Instatiates a hash map object
        Map < Integer, String > map = new HashMap < Integer, String > ();

        // By using put() method is to add
        // objects in a hash map
        map.put(10, "C");
        map.put(20, "C++");
        map.put(30, "JAVA");
        map.put(40, "C");
        map.put(50, "C++");

        // Display Map
        System.out.println("Map: " + map);

        // By using singletonMap() method is to
        // list the given key-value pair only
        map = Collections.singletonMap(30, "JAVA");

        // Display SingletonMap
        System.out.println("Collections.singletonMap(30,JAVA): " + map);
    }
}

Output

输出量

Map: {50=C++, 20=C++, 40=C, 10=C, 30=JAVA}
Collections.singletonMap(30,JAVA): {30=JAVA}


翻译自: https://www.includehelp.com/java/collections-singletonmap-method-with-example.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值