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()

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.