Java HashMap forEach() Method
The forEach() method is used to perform a specified action on each mapping in the HashMap.
The syntax for the forEach() method is:
hashmap.forEach(BiConsumer<K, V> action)
Note: hashmap is an object of the HashMap class.
Parameter Description:
- action - The action to be performed
Return Value
It does not return any value.
Example
The following example demonstrates the use of the forEach() method:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> prices = new HashMap<>();
// Insert mappings into 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: ");
// Use forEach() with a lambda expression
prices.forEach((key, value) -> {
// Reduce the price by 10%
value = value - value * 10/100;
System.out.print(key + "=" + value + " ");
});
}
}
Executing the above program outputs:
Normal Price: {Pant=150, Bag=300, Shoes=200}
Discounted Price: Pant=135 Bag=270 Shoes=180
Note this line:
prices.forEach((key, value) -> {
// Reduce the price by 10%
value = value - value * 10/100;
System.out.print(key + "=" + value + " ");
});
In the above example, we pass an anonymous function lambda expression as a parameter to the forEach() method. The lambda expression reduces each element in the dynamic array by 10% and then outputs the result.
For more information on lambda expressions, visit Java Lambda Expressions.
Note: The forEach() method is different from the for-each loop. Java for-each is used to iterate over each element in an array.