English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode forEach() de HashMap Java permet d'exécuter une opération spécifiée sur chaque mapping de la carte de hachage.
La syntaxe de la méthode forEach() est :
hashmap.forEach(BiConsumer<K, V> action)
action - Opération à effectuer sur chaque mapping de HashMap
La méthode forEach() ne renvoie aucune valeur.
import java.util.HashMap; class Main { public static void main(String[] args) { // Créer HashMap HashMap<String, Integer> prices = new HashMap<>(); //Insérer une entrée dans HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("Prix de marché: "); + prices); System.out.print("Prix de réduction: "); // Passer l'expression lambda à forEach() prices.forEach((key, value) -> { // La valeur diminue10% value = value - value * 10/100; System.out.print(key + "=" + value + " "); }); } }
Résultat de sortie
Prix de marché: {Pant=150, Bag=300, Shoes=200} Discount price: Pant=135 Bag=270 Shoes=180
In the above example, we created a hash map named prices. Note the code,
prices.forEach((key, value) -> { value = value - value * 10/100; System.out.print(key + "=" + value + " "); });
We have setlambda expressionpassed as a parameter to the forEach() method. Here,
The forEach() method performs the operation specified by the lambda expression for each entry of the hash table
The lambda expression reduces each value10%, and print all keys and reduced values
For more information about lambda expressions, please visitJava Lambda expressions.
Note: forEach() method with for-each loop is different. We can useJava for-each loopTraverse each entry of the hash table.