To check if Value exists in HashMap, we use the containsValue(Object key) method provided by HashMap.
boolean containsValue(Object key) searches the HashMap for the given value and returns true if one or more keys to the specified value are found.
Lets see some examples on containsValue(Object key) method
Example : Check if Value exists in HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kscodes.sampleproject; import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("USD", "American Dollar"); hashMap.put("AUD", "Australian Dollar"); hashMap.put("EUR", "Euro"); hashMap.put("JPY", "Japan Yen"); System.out.println("The HashMap has following elements::"); System.out.println(hashMap); System.out.println("****************************************"); boolean isJpyValueExists = hashMap.containsValue("Japan Yen"); System.out.println("Does the HashMap have 'Japan Yen' as Value :: " + isJpyValueExists); boolean isAbcExists = hashMap.containsValue("ABC Anything"); System.out.println("Does the HashMap have 'ABC Anything' as Value :: " + isAbcExists); } } |
Output
1 2 3 4 5 |
The HashMap has following elements:: {JPY=Japan Yen, EUR=Euro, USD=American Dollar, AUD=Australian Dollar} **************************************** Does the HashMap have 'Japan Yen' as Value :: true Does the HashMap have 'ABC Anything' as Value :: false |