// 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,使用默认值“北京”
}
}