Java HashMap putAll() Method
The putAll() method inserts all specified key/value pairs into the HashMap.
The syntax of the putAll() method is:
hashmap.putAll(Map m)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- m - contains the mappings to be inserted into the HashMap
Return Value
Returns no value.
Example
The following example demonstrates the use of the putAll() 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
)
;
// Create another HashMap
HashMap
<
Integer
, String
sites2
=
new
HashMap
<>
(
)
;
sites2.
put
(
1
,
"Weibo"
)
;
// Existing entries will be replaced
sites2.
put
(
4
,
"Wiki"
)
;
// Add all mappings from sites to sites2
sites2.
putAll
(
sites
)
;
System
.
out
.
println
(
"sites2 HashMap: "
sites2
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
sites2 HashMap: {1=Google, 2=Runoob, 3=Taobao, 4=Wiki}
In the above example, we created two HashMaps: sites and site2. We then used the putAll() method to insert the key/value of sites into site2. Since key 1 in site2 already exists, the value of site replaces the value of site2.
Insert a Single key/value Java HashMap put() Method.
Java HashMap