Java HashMap containsValue() Method
The containsValue()
method checks if the hashMap contains a mapping for the specified value.
The syntax for the containsValue()
method is:
hashmap.containsValue(Object value)
Note: hashmap
is an object of the HashMap class.
Parameter Description:
value
- The value to be checked.
Return Value
Returns true
if the hashMap contains a mapping for the specified value, 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, "tutorialpro");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check if the value "tutorialpro" exists in the map
if(sites.containsValue("tutorialpro")) {
System.out.println("tutorialpro exists in sites");
}
}
}
Output of the above program:
sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
tutorialpro exists in sites
For non-existing values, we can perform an insert operation:
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, "tutorialpro");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check if the value "Wiki" exists, if not, insert the key/value pair
if(!sites.containsValue("Wiki")) {
sites.put(4, "Wiki");
}
System.out.println("Updated sites HashMap: " + sites);
}
}
Output of the above program:
sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Updated sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao, 4=Wiki}
Note: We can also achieve the same result using the HashMap putIfAbsent() method.