Java Hashmap Containsvalue
# Java HashMap containsValue() Method
[ Java HashMap](#)
The containsValue() method checks if a mapping for the specified value exists in the hashMap.
The syntax for the containsValue() method is:
hashmap.containsValue(Object value)
**Note:** hashmap is an object of the HashMap class.
**Parameter Description:**
* value - value
### Return Value
Returns true if a mapping for 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 sites =new HashMap();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "");
sites.put(3, "Taobao");
System.out.println("sites HashMap: "+ sites);
// Check if the value "" exists in the mapping
if(sites.containsValue("")){
System.out.println(" exists in sites");
}
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=, 3=Taobao} exists in sites
For values that do not exist, we can perform an insert operation:
## Example
import java.util.HashMap;
class Main {
public static void main(String[] args){
// Create a HashMap
HashMap sites =new HashMap();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "");
sites.put(3, "Taobao");
System.out.println("sites HashMap: "+ sites);
// Check if the value "Wiki" exists, if not, insert the 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=, 3=Taobao}Updated sites HashMap: {1=Google, 2=, 3=Taobao, 4=Wiki}
**Note:** We can also use the [HashMap putIfAbsent() method](#) to perform the same operation.
[ Java HashMap](#)
YouTip