English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java HashMap forEach() method is used to perform a specified operation on each mapping of the hash map.
The syntax of forEach() method is:
hashmap.forEach(BiConsumer<K, V> action)
action - Operation performed on each mapping of HashMap
The forEach() method does not return any value.
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating HashMap HashMap<String, Integer> prices = new HashMap<>(); //Inserting entries into HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("Market Price: "); + prices); System.out.print("Discount Price: "); // Pass the lambda expression to forEach() prices.forEach((key, value) -> { // Value Decrease10% value = value - value * 10/100; System.out.print(key + "=" + value + " "); }); } }
Output Result
Market Price: {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 executes the operation specified by the lambda expression for each entry of the hash table
Lambda expressions will reduce 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.