Java HashMap forEach() Method

Java HashMap Java HashMap

The forEach() method is used to perform the specified operation on each mapping in the HashMap.

The syntax of the forEach() method is:

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

Note:hashmap is an object of the HashMap class.

Parameter Description:

  • action - the operation to be performed

Return Value

No return 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 mapping entries 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 value price by 10 percent
            value = value - value * 10/100;
            System.out.print(key + "=" + value + " ");
        });
    }
}

Executing the above program outputs the result:

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

Note this line:

prices.forEach((key, value) -> {
    // value 价格减少百分之 10
    value = value - value * 10/100;
    System.out.print(key + "=" + value + " ");
});

In the above example, we pass the anonymous function lambda expression as a parameter to the forEach() method. The lambda expression reduces each element in the dynamic array by 10 percent and then outputs the result.

For more information about lambda expressions, please visitJava Lambdaexpression.

Note:The forEach() method is different from the for-each loop.Java for-eachUsed to traverse each element in the array.

Java HashMap Java HashMap

Other extensions