Java HashMap containsValue() Method
The containsValue() method checks whether the mapping corresponding to the specified value exists in the HashMap.
The syntax of the containsValue() method is:
hashmap.containsValue(Object value)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- value - the value
Return Value
Returns true if the mapping corresponding to the specified value exists in the HashMap, otherwise returns false.
Example
The following example demonstrates the use of the containsValue() 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
)
;
// Check whether the value "Java" exists in the mapping
if
(
sites.
containsValue
(
"Runoob"
)
)
{
System
.
out
.
println
(
"Runoob exists in sites"
)
;
}
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Runoob 存在于 sites 中
For non-existent values, we can perform an insertion:
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
)
;
// Check whether the value is Wiki; if not, insert this key/value pair
// Use the ! symbol to negate the boolean result
if
(
!
sites.
containsValue
(
"Wiki"
)
)
{
sites.
put
(
4
,
"Wiki"
)
;
}
System
.
out
.
println
(
"Updated sites HashMap: "
sites
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Runoob, 3=Taobao, 4=Wiki}
**Note:** We can also use HashMap putIfAbsent() Methodperforms the same operation.
Java HashMap