Java HashMap replace() Method
The replace() method replaces the value corresponding to the specified key in the HashMap.
The syntax of the replace() method is:
hashmap.replace(K key, V newValue)
或
hashmap.replace(K key, V oldValue, V newValue)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- oldValue - the old value
- newValue - the new value
Return Value
If oldValue does not exist, it replaces the value corresponding to the key and returns the old value of the key; if oldValue exists, it returns true on successful replacement; if the key does not exist, it returns null.
Example
The following example demonstrates the use of the replace() method:
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
)
;
// Replace the mapping for key 2
String
value
=
sites.
replace
(
2
,
"Wiki"
)
;
System
.
out
.
println
(
"Replaced Value: "
value
)
;
System
.
out
.
println
(
"Updated HashMap: "
sites
)
;
}
}
The output of the above program is:
Replaced Value: Runoob
Updated HashMap: {1=Google, 2=Wiki, 3=Taobao}
The HashMap replace() method with the old value:
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
)
;
// Replace the mapping {1 = Google}, perform the replacement
sites.
replace
(
1
,
"Google"
,
"Wiki"
)
;
// Returns true
// The mapping {2 = Weibo} does not exist, no operation is performed
sites.
replace
(
2
,
"Weibo"
,
"Zhihu"
)
;
// Returns false
System
.
out
.
println
(
"sites after replace():\n"
sites
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
sites after replace():
{1=Wiki, 2=Runoob, 3=Taobao}
Java HashMap