Java HashMap forEach()

The syntax of the forEach() method is:

hashmap.forEach(BiConsumer<K, V> action)

Here, hashmap is an object of the HashMap class.


forEach() Parameters

The forEach() method takes a single parameter.

  • action - actions to be performed on each mapping of the HashMap

forEach() Return Value

The forEach() method does not return any value.


Example: Java HashMap forEach()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create a HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("Normal Price: " + prices);

    System.out.print("Discounted Price: ");

    // pass lambda expression to forEach()
    prices.forEach((key, value) -> {

      // decrease value by 10%
      value = value - value * 10/100;
      System.out.print(key + "=" + value + " ");
    });
  }
}

Output

Normal Price: {Pant=150, Bag=300, Shoes=200}
Discounted Price: Pant=135 Bag=270 Shoes=180 

In the above example, we have created a hashmap named prices. Notice the code,

prices.forEach((key, value) -> {
  value = value - value * 10/100;
  System.out.print(key + "=" + value + " ");  
});

We have passed the lambda expression as an argument to the forEach() method. Here,

  • the forEach() method performs the action specified by lambda expression for each entry of the hashmap
  • the lambda expression reduces each value by 10% and prints all the keys and reduced values

To learn more about lambda expression, visit Java Lambda Expressions.

Note: The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to loop through each entry of the hashmap.

Did you find this article helpful?