English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation orientée objet (I)

Java Programmation orientée objet (II)

Java Programmation orientée objet (III)

Gestion des exceptions Java

Java List

Java Queue (file d'attente)

Java Map Collections

Java Set Collections

Java Entrée Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Utilisation et exemple de la méthode forEach() de HashMap Java

Java HashMap methods

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)

Paramètres de forEach()

  • action - Opération à effectuer sur chaque mapping de HashMap

Retour de la valeur de forEach()

La méthode forEach() ne renvoie aucune valeur.

Exemple : Java HashMap forEach()

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.

Java HashMap methods