HashMap containsValue() Method in Java

Published by user on

The containsValue(V value) method of HashMap checks if the map contains the specified value or not. It returns true if the map contains the specified value otherwise it returns false. Some implementations of map throw NullPointerException if the value is null.

As HashMap supports null values. So, we can use this method safely with the null value.

Syntax

boolean containsValue(V value)

Parameters

The value to check its presence in the map

Program 1

The below program describes the use of containsValue() method.

import java.util.HashMap;
import java.util.Map;

public class HashMapContainsValueExample {

    public static void main(String[] args) {

        Map < Integer, String > map = new HashMap < > ();
        map.put(101, "John");
        map.put(102, "Adam");
        map.put(103, "Ricky");
        map.put(104, "Chris");

        boolean isRickyPresent = map.containsValue("Ricky");
        boolean isShaunPresent = map.containsValue("Shaun");
        boolean isNullPresent = map.containsValue(null);

        System.out.println("Map elements: " + map);
        System.out.println("Does map contain the value Ricky: " + isRickyPresent);
        System.out.println("Does map contain the value Shaun: " + isShaunPresent);
        System.out.println("Does map contain the value null: " + isNullPresent);
    }
}

Output

Map elements: {101=John, 102=Adam, 103=Ricky, 104=Chris}
Does map contain the value Ricky: true
Does map contain the value Shaun: false
Does map contain the value null: false

Explanation

  • Create a new HashMap
  • Add values to it
  • Check if the map contains the value using the containsValue method
  • When we passed Ricky then the containsValue method returned true, for Shaun it returned false
  • Finally, for the null value, the call to the method returned false
Categories: Java