Map.getOrDefault()方法

    // Defaultable methods

    /**
     * Returns the value to which the specified key is mapped, or
     * {@code defaultValue} if this map contains no mapping for the key.
     *
     * @implSpec
     * The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties.
     *
     * @param key the key whose associated value is to be returned
     * @param defaultValue the default mapping of the key
     * @return the value to which the specified key is mapped, or
     * {@code defaultValue} if this map contains no mapping for the key
     * @throws ClassCastException if the key is of an inappropriate type for
     * this map
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified key is null and this map
     * does not permit null keys
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @since 1.8
     */
    default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

默认方法返回指定键映射到的值,如果此映射不包含键的映射,则返回 {@code defaultValue}。 @implSpec 默认实现不保证此方法的同步或原子性属性。任何提供原子性保证的实现都必须覆盖此方法并记录其并发属性。 @param key 要返回其关联值的键 @param defaultValue 键的默认映射 @return 指定键映射到的值,如果此映射不包含键的映射,则返回 {@code defaultValue} @throws ClassCastException 如果键的类型不适合此映射 (optional) @throws NullPointerException 如果指定的键为 null 并且此映射不允许 null键 (可选) @since 1.8 default V getOrDefault(Object key, V defaultValue) { V v;返回 (((v = get(key)) != null) || containsKey(key)) ? v : 默认值; }

这是源码,意思就是当Map集合中有这个key时,就使用这个key对应的value值,如果没有这个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,使用默认值“北京”
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值