Java HashMap put() Method
The put() method inserts the specified key/value pair into the HashMap.
The syntax of the put() method is:
hashmap.put(K key,V value)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- value - the value
Return Value
If the value corresponding to the inserted key already exists, a value replacement is performed and the old value is returned; if it does not exist, an insertion is performed and null is returned.
Example
The following example demonstrates the use of the put() method (the value corresponding to the key does not exist):
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
(
"HashMap: "
sites
)
;
}
}
The output of the above program is:
HashMap: {1=Google, 2=Runoob, 3=Taobao}
In the above example, we created a HashMap named sites, and then used the put() method to insert this key/value mapping into the HashMap.
Insert Multiple key/value Pairs Java HashMap putAll() Method.
**Note:** Each item is inserted into the HashMap at random.
Example of inserting when the value corresponding to the key already exists:
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
(
"HashMap: "
sites
)
;
// Add a duplicate key element
String
value
=
sites.
put
(
1
,
"Weibo"
)
;
System
.
out
.
println
(
"Modified HashMap: "
sites
)
;
// View the replaced value
System
.
out
.
println
(
"Replaced value: "
value
)
;
}
}
The output of the above program is:
修改后的 HashMap: {1=Weibo, 2=Runoob, 3=Taobao}
替换的值: Google
Java HashMap