English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode containsKey() de HashMap Java vérifie si une correspondance pour la clé spécifiée existe dans la carte de hachage.
La syntaxe de la méthode containsKey() est :
hashmap.containsKey(Object key)
key - Vérification de la correspondance de la clé dans la carte de hachage
Si la carte de hachage contient une correspondance pour la clé spécifiée, renvoie true
Si la carte de hachage ne contient pas de correspondance pour la clé spécifiée, renvoie false
import java.util.HashMap; class Main { public static void main(String[] args){ //Création de HashMap HashMap<String, String> details = new HashMap<>(); //Ajoutez la carte au HashMap details.put("Name", "w3codebox"); details.put("Domain", "oldtoolbag.com"); details.put("Location", "Nepal"); System.out.println("w3Détails de codebox: \n" + details); //Vérifiez si la clé Domain existe if(details.containsKey("Domain")) { System.out.println("Domain existe dans Hashmap"); } } }
Output result
w3Détails de codebox: {Domain=oldtoolbag.com, Name=w3codebox, Location=Nepal} Domain existe dans Hashmap
Dans l'exemple précédent, nous avons créé une carte de hachage. Notez ces expressions,
details.containsKey("Domain") // Retourne true
Ici, hashmap contient une carte avec une clé Domain. Par conséquent, le bloc if est exécuté et la méthode containsKey() retourne true et l'instruction.
import java.util.HashMap; class Main { public static void main(String[] args){ // Créez un HashMap HashMap<String, String> countries = new HashMap<>(); // Ajoutez la carte au HashMap countries.put("USA", "Washington"); countries.put("Australia", "Canberra"); System.out.println("HashMap:\n" + countries); // Vérifiez si la clé Spain existe if(!countries.containsKey("Spain")) { // Si la clé n'existe pas, ajoutez l'entrée countries.put("Spain", "Madrid"); } System.out.println("HashMap mis à jour:\n" + countries); } }
Output result
HashMap: {USA=Washington, Australia=Canberra} Updated HashMap: {USA=Washington, Australia=Canberra, Spain=Madrid}
In the above example, please note the following expression:
if(!countries.containsKey("Spain")) {..}
Here, we used the containsKey() method to check if there is a mapping for Spain in the hash map. Since we used the negation symbol (!), if this method returns false, the if block will be executed.
Therefore, a new mapping is only added if there is no specified key mapping in the hashmap.
Note: We can also useHashMap putIfAbsent()Methods perform the same task.