English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Si la clé spécifiée n'a pas été trouvée dans HashMap, la méthode putIfAbsent() de Java HashMap insère la clé spécifiée/La valeur de la carte est insérée dans HashMap.
La syntaxe de la méthode putIfAbsent() est :
hashmap.putIfAbsent(K key, V value)
La méthode putIfAbsent() a deux paramètres.
clé - La valeur spécifiée est mappée à la clé
valeur - La valeur est associée à la clé
Si la clé spécifiée existe déjà dans le graph de hash, retourne la valeur associée à la clé.
Si la clé spécifiée n'existe pas dans la carte de hash, retourne null
Note: Si une valeur null a été spécifiée précédemment, retourne null.
import java.util.HashMap; class Main { public static void main(String[] args){ // Créer HashMap HashMap<Integer, String> languages = new HashMap<>(); // ajouter des mappages à HashMap languages.put(1, "Python"); languages.put(2, "C"); languages.put(3, "Java"); System.out.println("Languages: " + languages); //La clé n'est pas dans HashMap languages.putIfAbsent(4, "JavaScript"); //La clé apparaît dans HashMap languages.putIfAbsent(2, "Swift"); System.out.println("Mise à jour des Languages: " + languages); } }
Output result
Languages: {1=Python, 2=C, 3=Java} Updated Languages: {1=Python, 2=C, 3=Java, 4=JavaScript}
In the above example, we created a hash map named languages. Note this line,
languages.putIfAbsent(4, "JavaScript");
Here, the key4Not associated with any value. Therefore, the putifAbsent() method will add the mapping {4 = JavaScript} added to the hash map.
Note this line,
languages.putIfAbsent(2, "Swift");
Here, the key2Already associated with Java. Therefore, the putIfAbsent() method will not add the mapping {2 = Swift} added to the hash map.
NoteWe have used the put() method to add a single mapping to the hash map. For more information, please visitJava HashMap put().