English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap containsValue() method checks if the specified value exists in one or more mappings in the hash map.
The syntax of the containsValue() method is:
hashmap.containsValue(Object value)
value- The value exists in one or more mappings in the HashMap
If the specified value exists, it returns true
If the specified value does not exist, it returns false
import java.util.HashMap; class Main { public static void main(String[] args){ // Create HashMap HashMap<Integer, String> languages = new HashMap<>(); //Add the mapping to the HashMap languages.put(1, "Python"); languages.put(2, "Java"); languages.put(3, "JS"); System.out.println("HashMap" + languages); //Check if the value Java exists if(languages.containsValue("Java")) { System.out.println("Java exists in the list."); } } }
Output Result
HashMap{1=Python, 2=Java, 3=JS} Java exists in the list.
In the above example, we created a hash map named languages. Note these expressions,
languages.containsValue("Java") // Returns true
Here, the specified value Java exists in the mapping ({2 = Java} Therefore, the if code block is executed, and the containsValue() method will return true and the statement.
import java.util.HashMap; class Main { public static void main(String[] args){ // Create HashMap HashMap<String, String> countries = new HashMap<>(); //Add the mapping to the HashMap countries.put("Washington", "USA"); countries.put("Canberra", "Australia"); System.out.println("HashMap:\n" + countries); //Check if the value Spain exists if(!countries.containsValue("Spain")) { //If the value does not exist, add the entry countries.put("Madrid", "Spain"); } System.out.println("Updated HashMap:\n" + countries); } }
Output Result
HashMap: {Canberra=Australia, Washington=USA} Updated HashMap: {Madrid=Spain, Canberra=Australia, Washington=USA}
In the above example, please note the following expression:
if(!countries.containsValue("Spain")) {..}
Here, we used the containsValue() method to check if the specified value Spain exists in the hash map. Since we used the negation symbol (!), if this method returns false, the if block will be executed
Therefore, a new mapping is only added if there is no existing mapping for the specified value in the hash map.
Note: We can also useHashMap putIfAbsent()Methods perform the same task.