Java HashMapcontainsValue

In this tutorial, we will learn about the Java HashMap.containsValue() function, and learn how to use this function to check if this HashMap contains specified value, with the help of examples.

containsValueObject value

HashMap.containsValue() returns true if this HashMap maps one or more keys to the specified value. If there is no key that maps to the specified value, then containsValue() returns false.

The syntax of containsValue() function is

containsValue(Object value)

where

Parameter Description
value The object which we are checking if present in this HashMap.

Returns

The function returns boolean value.

Examples

1 containsValuevalue Value present

In this example, we will initialize a HashMap hashMap with mappings from String to Integer. Using HashMap.containsValue() method, we will check if the value "3" is present in this hashMap. Since, the value "3" is present in hashMap, containsValue() should return true.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = new HashMap<>();
		hashMap.put("A",1);
		hashMap.put("B",2);
		hashMap.put("C",3);
		hashMap.put("D",4);

		int value = 3;
		boolean result = hashMap.containsValue(value);
		System.out.println("Does the HashMap contains value ? : " + result);
	}
}

Output

Does the HashMap contains value ? : true

2 containsValuevalue Value not present

In this example, we will initialize a HashMap hashMap with mappings from String to Integer. Using HashMap.containsValue() method, we will check if the value "5" is present in this hashMap. Since, the value "5" is not present in hashMap, containsValue() should return false.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = new HashMap<>();
		hashMap.put("A",1);
		hashMap.put("B",2);
		hashMap.put("C",3);
		hashMap.put("D",4);

		int value = 5;
		boolean result = hashMap.containsValue(value);
		System.out.println("Does the HashMap contains value ? : " + result);
	}
}

Output

Does the HashMap contains value ? : false

3 containsValuevalue When HashMap is null

In this example, we will initialize a HashMap hashMap with null. Calling HashMap.containsValue() method on null object should throw java.lang.NullPointerException.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = null;

		int value = 5;
		boolean result = hashMap.containsValue(value);
		System.out.println("Does the HashMap contains value ? : " + result);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:8)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.containsValue() function, and also learnt how to use this function with the help of examples.