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

Java HashMap replaceAll() Method

Java HashMap replaceAll() Method

Java HashMap Java HashMap

The replaceAll() method replaces all mappings in the HashMap with the results produced by the given function.

The replaceAll() method is used to replace every element in the array with the given operation content.


hashmap.replaceAll(Bifunction function)

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

Parameter Description:

Return Value

Returns no value; it only replaces all values in the HashMap.

Example

operator - the element or a series of operations to be replaced into the dynamic array

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a HashMap

        HashMap

<

Integer

, String

sites

=

new

HashMap

<>

(

)

;

       

// Add some elements to the HashMap

        sites.

put

(

1

,

"Google"

)

;

        sites.

put

(

2

,

"Runoob"

)

;

        sites.

put

(

3

,

"Taobao"

)

;

       

System

.

out

.

println

(

"sites HashMap: "

sites

)

;

       

// Change all values to uppercase

        sites.

replaceAll

(

(

key, value

)

->

value.

toUpperCase

(

)

)

;

       

System

.

out

.

println

(

"Updated HashMap: "

sites

)

;

   

}

}

The output of the above program is:


sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Updated HashMap: {1=GOOGLE, 2=RUNOOB, 3=TAOBAO}

(key, value) -> value.toUpperCase() is an anonymous lambda expression. It converts all values in the HashMap to uppercase and returns them. To learn more, please visit To learn more about anonymous functions, please visit.

Replace all values with the square of the key:

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a HashMap

        HashMap

<

Integer

, Integer

numbers

=

new

HashMap

<>

(

)

;

       

// Add mappings to the HashMap

        numbers.

put

(

5

,

0

)

;

        numbers.

put

(

8

,

1

)

;

        numbers.

put

(

9

,

2

)

;

       

System

.

out

.

println

(

"HashMap: "

numbers

)

;

       

// Replace all values with the square of the key

        numbers.

replaceAll

(

(

key, value

)

->

key

key

)

;;

       

System

.

out

.

println

(

"Updated HashMap: "

numbers

)

;

   

}

}

The output of the above program is:

HashMap: {5=0, 8=1, 9=2}
Updated HashMap: {5=25, 8=64, 9=81}

Java HashMap Java HashMap