English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java HashMap remove()方法从与指定键关联的哈希映射中删除映射。
remove()方法的语法为:
hashmap.remove(Object key, Object value);
key - 删除键的映射
value(可选)-仅当指定键映射到指定值时才删除映射
remove()方法删除映射并返回:
与指定键关联的前一个值
如果删除映射,则为true
Note:如果指定的键映射到null值或该键在哈希映射中不存在,则该方法返回null。
import java.util.HashMap; class Main { public static void main(String[] args){ //Créer HashMap HashMap<Integer, String> languages = new HashMap<>(); //Ajouter la correspondance à HashMap languages.put(1, "Python"); languages.put(2, "C"); languages.put(3, "Java"); System.out.println("Languages: ") + languages); //supprimer la clé2de la correspondance languages.remove(2); // Retourne C System.out.println("Les Languages mis à jour: ") + languages); } }
Résultat de la sortie
Languages: {1=Python, 2=C, 3=Java} Les Languages mis à jour: {1=Python, 3=Java}
Dans l'exemple ci-dessus, nous avons créé une carte de hachage nommée languages. Ici, la méthode remove() n'a pas de paramètre value optionnel. Par conséquent, la correspondance avec la clé2La correspondance a été supprimée de la carte de hachage.
import java.util.HashMap; class Main { public static void main(String[] args) { //Créer un HashMap HashMap<String, String> countries = new HashMap<>(); //Insérer un élément dans HashMap countries.put("Washington", "Amérique"); countries.put("Ottawa", "Canada"); countries.put("Kathmandu", "Népal"); System.out.println("Countries: ") + countries); // Suppression de la correspondance {Ottawa=Canada} countries.remove("Ottawa", "Canada"); // return true // Suppression de la correspondance {Washington=USA} countries.remove("Washington", "USA"); // return false System.out.println("Après remove() les Countries: ") + countries); } }
Résultat de la sortie
Pays: {Kathmandu=Népal, Ottawa=Canada, Washington=Amérique} After remove(): Countries: {Kathmandu=Nepal, Washington=America}
In the above example, we created a hash map named countries. Note this line,
countries.remove("Ottawa", "Canada");
Here, the remove() method includes an optional value parameter (Canada). Therefore, the mapping from the key Ottawa to the value Canada has been removed from the hash map.
But please note that
countries.remove("Washington", "USA");
In this case, the hash map does not contain a mapping with the key Washington and value USA. Therefore, there is no mapping Washington = America removed from the hash map.
NoteWe can useJava HashMap clear()The method removes all mappings from the hash map.