Java HashMap containsValue()

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()

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

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.