The syntax of the containsValue()
method is:
hashmap.containsValue(Object value)
Here, hashmap is an object of the HashMap
class.
containsValue() Parameter
The containsValue()
method takes a single parameter.
- value - value is present in one or more mappings in the
HashMap
containsValue() Return Value
- returns
true
if the specified value is present - returns
false
if the specified value is not present
Example 1: Java HashMap containsValue()
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<Integer, String> languages = new HashMap<>();
// add mappings to HashMap
languages.put(1, "Python");
languages.put(2, "Java");
languages.put(3, "JS");
System.out.println("HashMap" + languages);
// check if value Java is present
if(languages.containsValue("Java")) {
System.out.println("Java is present on the list.");
}
}
}
Output
HashMap{1=Python, 2=Java, 3=JS} Java is present on the list.
In the above example, we have created a hashmap named languages. Notice the expressions,
languages.containsValue("Java") // returns true
Here, the specified value Java is present in the mapping ({2=Java}
). Hence, the containsValue()
method returns true
and statement inside if
block is executed.
Example 2: Add Entry to HashMap if Value is already not present
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<String, String> countries = new HashMap<>();
// add mappings to HashMap
countries.put("Washington", "USA");
countries.put("Canberra", "Australia");
System.out.println("HashMap:\n" + countries);
// check if the value Spain is present
if(!countries.containsValue("Spain")) {
// add entry if Value already not present
countries.put("Madrid", "Spain");
}
System.out.println("Updated HashMap:\n" + countries);
}
}
Output
HashMap: {Canberra=Australia, Washington=USA} Updated HashMap: {Madrid=Spain, Canberra=Australia, Washington=USA}
In the above example, notice the expression,
if(!countries.containsValue("Spain")) {..}
Here, we have used the containsValue()
method to check if the specified value Spain is present in the hashmap. Since we have used the negate sign !
, the if
block is executed if the method returns false
.
Hence, the new mapping is added only if there is no mapping for the specified value in the hashmap.
Note: We can also use the HashMap putIfAbsent() method to perform the same task.