Java HashMap remove() Method
The remove() method is used to delete the key/value pair corresponding to the specified key in the HashMap.
The syntax of the remove() method is:
hashmap.remove(Object key, Object value);
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- value (optional) - the value corresponding to the key in the key/value pair
Return Value
If a key is specified, it returns the value associated with the specified key; if the specified key maps to null or the key does not exist in the HashMap, this method returns null.
If both key and value are specified, it returns true on successful deletion, otherwise it returns false.
Example
The following example demonstrates the use of the remove() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
HashMap
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
sites.
put
(
3
,
"Taobao"
)
;
System
.
out
.
println
(
"HashMap: "
sites
)
;
// Remove the mapping for key 2
String
siteName
=
sites.
remove
(
2
)
;
// return Runoob
System
.
out
.
println
(
"Return value: "
siteName
)
;
System
.
out
.
println
(
"HashMap after removal: "
sites
)
;
}
}
The output of the above program is:
HashMap: {1=Google, 2=Runoob, 3=Taobao}
返回值: Runoob
删除后的 HashMap: {1=Google, 3=Taobao}
In the above example, we created a HashMap named sites, and then used the remove() method to delete the value corresponding to the specified key of sites, and the return value is that value.
The remove() method with both key and value parameters:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
HashMap
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
sites.
put
(
3
,
"Taobao"
)
;
System
.
out
.
println
(
"HashMap: "
sites
)
;
// Remove the mapping for key 2
Boolean
flag1
=
sites.
remove
(
1
,
"Google"
)
;
// return true
Boolean
flag2
=
sites.
remove
(
2
,
"Weibo"
)
;
// return false
System
.
out
.
println
(
"Return value flag1: "
flag1
)
;
System
.
out
.
println
(
"Return value flag2: "
flag2
)
;
System
.
out
.
println
(
"HashMap after removal: "
sites
)
;
}
}
The output of the above program is:
返回值 flag1: true
返回值 flag2: false
删除后的 HashMap: {2=Runoob, 3=Taobao}
In the above example, we created a HashMap named sites that contains 3 elements. Note these two lines:
Boolean flag1 = sites.remove(1, "Google"); // 存在的键值对返回 true
Boolean flag2 = sites.remove(2, "Weibo"); // 不存在的键值对返回 false
The remove() method includes key and value; if the HashMap contains this key/value pair, it returns true, otherwise it returns false.
Java HashMap