What is the containsValue method in Java HashMaps?

containsValue() is a built-in method defined in the HashMap class in Java. The class is available in the java.util package.

The following is the method prototype:

boolean containsValue(Object value)

Functionality

Unlike most data structures that require an integer index to access a particular memory location, HashMaps store data in a key-value pair. This allows the user to associate a unique key of any data type to every data value.

We use the containsValue() method to check whether the HashMap maps one or more keys onto the passed value.

The containsValue() method

Parameters and return value

The method takes the following as its input argument:

  • value: The value to be checked within the HashMap. This is of type Object, which is the base class for all Java Classes. This means that the value to be checked may be of any valid type.

The containsValue() method returns true if the specified value is found to be mapped onto by any key(s) within the HashMap.

Otherwise, the method returns false.

Code

import java.util.HashMap;
public class Main{
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
// Mapping string values to int keys
hash_map.put(2, "Edpresso");
hash_map.put(4, "Shots");
hash_map.put(6, "of");
hash_map.put(8, "Dev");
hash_map.put(10, "Knowledge");
// Displaying the HashMap
System.out.println("HashMap: \n" + hash_map);
// Checking for the Value 'Knowledge'
System.out.println("\nContains 'Knowledge'?\n" +
hash_map.containsValue("Knowledge"));
// Checking for the Value 'Hello'
System.out.println("\nContains 'Hello'?\n" +
hash_map.containsValue("Hello"));
}
}

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved