Map.getOrDefault()方法

default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;

    }

这是源码,意思就是当Map集合中有这个key时,就使用这个key值,如果没有就使用默认值defaultValue

下面就具体的例子,再说明一下:

public class Demo13 {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("name", "lxj");
        map.put("age", "24");
        map.put("sex", "女");
        String name = map.getOrDefault("name", "test");
        System.out.println(name);// lxj,map中存在name,获得name对应的value
        String address = map.getOrDefault("address", "北京");
        System.out.println(address);// 北京,map中不存在address,使用默认值“北京”
    }
}

猜你喜欢

转载自blog.csdn.net/lxj_1993/article/details/79798963
今日推荐