How to Check if key exists in HashMap
To check if Key exists in HashMap, we use the containsKey(Object key) method provided by HashMap.
boolean containsKey(Object key) searches the HashMap for the given key and returns boolean(true/false).
Lets see some examples on containsKey(Object key) method
Example : Check if Key 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 isJpyExists = hashMap.containsKey("JPY"); System.out.println("Does the HashMap have 'JPY' as Key :: " + isJpyExists); boolean isAbcExists = hashMap.containsKey("ABC"); System.out.println("Does the HashMap have 'ABC' as Key :: " + 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 'JPY' as Key :: true Does the HashMap have 'ABC' as Key :: false |