English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode compute() de HashMap Java calcule une nouvelle valeur et la lie à la clé spécifiée dans la carte de hachage.
La syntaxe de la méthode compute() est :
hashmap.compute(K key, BiFunction remappingFunction)
compute() méthode a deux paramètres :
key - Clé associée à la valeur calculée
remappingFunction - PourCléFonction de calcul de la nouvelle valeur
Note:remappingFunction peut accepter deux paramètres.
Retourne la nouvelle valeur associée à la clé
Si il n'y a pas de valeur associée à la clé, retourne null
Note:Si le résultat de remappingFunction est null, la valeur spécifiée sera suppriméeCléde la correspondance.
import java.util.HashMap; class Main { public static void main(String[] args) { //Créer une HashMap HashMap<String, Integer> prices = new HashMap<>(); //Insérer une entrée dans la HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: " + prices); //Avec10Pour recalculer le prix des chaussures en pourcentage de réduction int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100); System.out.println("Prix de réduction des chaussures: " + newPrice); //Imprimer la HashMap mise à jour System.out.println("Nouvelle HashMap: " + prices); } }
Résultat de la sortie
HashMap: {Pant=150, Bag=300, Shoes=200} Prix de réduction des chaussures: 180 Nouvelle HashMap: {Pant=150, Bag=300, Shoes=180
Dans l'exemple ci-dessus, nous avons créé une carte de hachage nommée prices. Notez l'expression
prices.compute("Shoes", (key, value) -> value - value * 10/100)
Here,
(key, value) -> value - value * 10/100 - This is a lambda expression. It will reduce the original price of the shoes10For more information on lambda expressions, please visitJava Lambda expressions
prices.compute() - Associate the new value returned by the lambda expression with the mapping of Shoes.
NoteAccording to the official Java documentation,HashMap merge()The method is simpler than the compute() method.
Recommended reading
HashMap computeIfAbsent() - If the specified key is not mapped to any value, calculate the value
HashMap computeIfPresent() - If the specified key is already mapped to a value, calculate the value