English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
如果在哈希映射中找不到指定键的映射,则Java HashMap getOrDefault()方法将返回指定的默认值。
否则,该方法返回与指定键对应的值。
getOrDefault()方法的语法为:
hashmap.get(Object key, V defaultValue)
key - 要返回其映射值的key
defaultValue - 如果找不到指定键的映射关系,则返回该默认值
返回与指定键关联的值
如果找不到指定键的映射,则返回指定的defaultValue
import java.util.HashMap; class Main { public static void main(String[] args) { // 创建 HashMap HashMap<Integer, String> numbers = new HashMap<>(); //向HashMap插入条目 numbers.put(1, "Java"); numbers.put(2, "Python"); numbers.put(3, "JavaScript"); System.out.println("HashMap: " + numbers); //键的映射存在于HashMap中 String value1 = numbers.getOrDefault(1, "Not Found"); System.out.println("key"}1的值: " + value1); //HashMap中不存在该键的映射 String value2 = numbers.getOrDefault(4, "Not Found"); System.out.println("key"}4value: " + value2); } }
Output result
HashMap: {1=Java, 2=Python, 3=JavaScript} key1value: Java key4value: Not Found
In the above example, we created a hash map named numbers. Note the expression
numbers.getOrDefault(1, "Not Found")
Here,
1 - to return the key mapping its value
Not Found - If the hash map does not contain the key, it will return the default value
Since the hashmap contains the mapping of the key1. Therefore, Java will return this value.
But, please note the following expression:
numbers.getOrDefault(4, "Not Found")
Here,
4 - to return the key mapping its value
Not Found - default value
Since the hash map does not contain the key4any map. Therefore, the default value Not Found will be returned.
Note: we can useHashMap containsKey()A method to check if a specific key exists in the hash map.