Java HashMap containsValue() Method

Java HashMap Java HashMap

The containsValue() method checks whether the specified value has a corresponding mapping in the hashMap.

The syntax of the containsValue() method is:

hashmap.containsValue(Object value)

Note:hashmap is an object of the HashMap class.

Parameter description:

  • value - the value

Return Value

Returns true if the specified value has a corresponding mapping in the hashMap, otherwise returns false.

Example

The following example demonstrates the usage 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, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Check whether the value "Java" exists in the mapping
        if(sites.containsValue("Example")) {
            System.out.println("Example exists in sites");
        }
    }
}

The output of the above program is:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
Example 存在于 sites 中

For values that do not exist, we can perform an insertion 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, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Check whether the value "Wiki" exists; if not, insert the key/value pair
        // Use the ! symbol to negate the boolean result
        if(!sites.containsValue("Wiki")) {
            sites.put(4, "Wiki");
        }
        System.out.println("Updated sites HashMap: " + sites);
    }
}

The output of the above program is:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Example, 3=Taobao, 4=Wiki}

Note:We can also useHashMap putIfAbsent() methodto perform the same operation.

Java HashMap Java HashMap

Other extensions