English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Si la clé spécifiée n'existe pas, alors la méthode merge() de Java HashMap ajoutera la clé spécifiée/La valeur de la carte de hachage est insérée dans la carte de hachage.
Mais, si la clé spécifiée est déjà associée à une valeur, alors cette méthode remplacera l'ancienne valeur par le résultat de la fonction spécifiée.
La syntaxe de la méthode merge() est :
hashmap.merge(key, value, remappingFunction)
La méthode merge() de hashmap utilise3Paramètres :
key - Pour spécifier la valeur associée à la clé
value - Si la clé est déjà associée à toute valeur, alors il faut la valeur associée à la clé
remappingFunction - Si la clé est déjà associée à une valeur, alors le résultat est associé à la clé.
Retourne la nouvelle valeur associée à la clé (key)
Si il n'y a pas de valeur associée à la clé (key), alors retourne null
Attention:Si le résultat de remappingFunction est null, alors la carte de hachage de la clé spécifiée sera supprimée.
import java.util.HashMap; class Main { public static void main(String[] args) { //创建 HashMap HashMap<String, Integer> prices = new HashMap<>(); //向HashMap插入条目 prices.put("Chaussettes", 200); prices.put("Sac", 300); prices.put("Pant", 150); System.out.println("HashMap: ") + prices); int returnedValue = prices.merge("Shirt", 100, (oldValue, newValue) -> old value + newValue); System.out.println("Prix du chemise: ") + returnedValue); //Imprimer la HashMap mise à jour System.out.println("Nouvelle HashMap: ") + prices); } }
输出结果
HashMap: {Pant=150, Sac=300, Chaussettes=200} Prix du chemise: 100 HashMap mis à jour: {Pant=150, Shirt=100, Sac=300, Chaussettes=200}
Dans l'exemple ci-dessus, nous avons créé une carte de hachage nommée prices. Notez l'expression
prices.merge("Shirt",}} 100, (oldValue, newValue) -> old value + newValue)
Ici, nous utilisons l'expression lambda (oldValue, newValue) -> oldValue + newValue) comme fonction remappingFunction. Pour plus d'informations sur les expressions lambda, veuillez visiterJava Lambda expressions.
Comme la clé Shirt n'existe pas dans prices, la méthode merge() met Shirt=100 insérer la carte. Et le résultat de remappingFunction sera ignoré.
import java.util.HashMap; class Main { public static void main(String[] args) { // 创建 HashMap HashMap<String, String> countries = new HashMap<>(); // 向HashMap插入条目 countries.put("Washington", "America"); countries.put("Canberra", "Australia"); countries.put("Madrid", "Spain"); System.out.println("HashMap: ") + countries); // Méthode de fusion de la clé Washington String returnedValue = countries.merge("Washington", "USA", (oldValue, newValue) -> old value + "/" + newValue); System.out.println("Washington: ") + returnedValue); // Imprimer la HashMap mise à jour System.out.println("Nouvelle HashMap: ") + countries); } }
输出结果
HashMap: {Madrid=Spain, Canberra=Australia, Washington=America} Washington: America/USA Nouvelle HashMap: {Madrid=Spain, Canberra=Australia, Washington=America/USA},
Dans l'exemple précédent, nous avons créé une carte de hachage nommée countries. Notez l'expression
countries.merge("Washington", "USA", (oldValue, newValue) -> old value + "/" + newValue)
在这里,我们使用了lambda表达式(oldValue, newValue) -> oldValue + "/" + newValue) 作为 remappingFunction。
由于键Washington已经存在countries中,所以旧值将由remappingFunction返回的值替换。因此,Washington 的映射包括值 America/USA。
import java.util.HashMap; class Main { public static void main(String[] args) { //创建 HashMap HashMap<String, Integer> prices1 = new HashMap<>(); //向HashMap插入条目 prices1.put("Pant", 230); prices1.put("Shoes", 350); System.out.println("HashMap 1: " + prices1); //创建另一个hashmap HashMap<String, Integer> prices2 = new HashMap<>(); //向HashMap插入条目 prices2.put("Shirt", 150); prices2.put("Shoes", 320); System.out.println("HashMap 2: " + prices2); // forEach()访问prices2的每个条目 // merge()将每个条目从prices2插入到prices1 prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> { //返回较小的值 if (oldValue < newValue) { return oldValue; } else { return newValue; } }); System.out.println("合并后的 HashMap: ", + prices1); } }
输出结果
HashMap 1: {Pant=230, Shoes=350} HashMap 2: {Shirt=150, Shoes=320} 合并后的 HashMap: {Pant=230, Shirt=150, Shoes=320}
在上面的示例中,我们创建了两个名为prices1和prices2的哈希映射。注意代码,
prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> { if (oldValue < newValue) { return oldValue; } else { return newValue; } });
在这里,HashMap forEach()方法访问哈希表prices2的每个条目,并将其合并到哈希表prices1中。我们使用了两个lambda表达式:
(key, value) -> prices.merge(...) - It accesses prices1each entry and pass it to the merge() method.
(oldValue, newValue) -> {...} - This is a remapping function (remappingFunction). It compares two values and returns the smaller one.
Since the key Shoes exists in both hash maps, the value of Shoes is replaced by the result of the remapping function (remappingFunction).
We can also use the putAll() method to merge two hash maps. However, if both hash maps have the same keys, the old value will be replaced by the new value
Unlike merge(), the putAll() method does not provide remapping functionality. Therefore, we cannot determine the value to be stored for repeated keys.
To learn more about the putAll() method, please visitJava HashMap putAll().