Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashMap forEach() Method

Java HashMap forEach() Method

Java HashMap Java HashMap

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

The syntax of the forEach() method is:


hashmap.forEach(BiConsumer action)

**Note:** hashmap is an object of the HashMap class.

Parameter Description:

Return Value

No value is returned.

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 value (price) by 10 percent

            value

=

value

value

10

/

100

;

           

System

.

out

.

print

(

key

"="

value

" "

)

;

       

}

)

;

   

}

}

The output of the above program is:


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

Note this line:


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

In the above example, we passed an anonymous lambda expression as the argument to the forEach() method; the lambda expression reduces each element in the dynamic array by 10 percent, then outputs the result.

For more information about lambda expressions, please visit Java Lambda expression.

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

Java HashMap Java HashMap