English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Se não encontrar o mapeamento da chave especificada no mapeamento de hash, o método getOrDefault() do Java HashMap retornará o valor padrão especificado.
Caso contrário, o método retorna o valor correspondente à chave especificada.
A sintaxe do método getOrDefault() é:
hashmap.get(Object key, V defaultValue)
key - para retornar seu mapeamentoO valorkey
defaultValue - Se não encontrar o mapeamento da relação da chave especificada, retorna o valor padrão
Retorna o valor associado à chave especificada
Se não encontrar o mapeamento da chave especificada, retorna o valor padrão especificado
import java.util.HashMap; class Main { public static void main(String[] args) { // Criar HashMap HashMap<Integer, String> numbers = new HashMap<>(); //Inserir entrada no HashMap numbers.put(1, "Java"); numbers.put(2, "Python"); numbers.put(3, "JavaScript"); System.out.println("HashMap: " + numbers); //O mapeamento da chave existe no HashMap String valor1 = numbers.getOrDefault(1, "Não Encontrado"); System.out.println("key"}1com o valor: " + value1); //Não há mapeamento da chave no HashMap String valor2 = numbers.getOrDefault(4, "Não Encontrado"); 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 of its mapping 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 of its mapping value
Not Found - Default value
Since the hash map does not contain the key4any map. Therefore, it will return the default value Not Found.
Note: We can useHashMap containsKey()Method to check if a specific key exists in the hash map.