Check If Key Exists in HashMap
In this tutorial, We will show you How to Check if Key Exists in HashMap using Java Program. The program was tested and output is shared in the same post.
CheckMapKey.java
package com.dineshkrish; import java.util.HashMap; import java.util.Map; public class CheckMapKey { public static void main(String[] args) { Map<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); numbers.put("Four", null); System.out.println("1. Is key 'One' Exists ?"); if (numbers.containsKey("One")) { System.out.println("YES - Value is : " + numbers.get("One")); } else { System.out.println("NO"); } System.out.println("\n2. Is key 'Two' Exists?"); if (numbers.containsKey("Two")) { System.out.println("YES - Value is : " + numbers.get("Two")); } else { System.out.println("NO"); } System.out.println("\n3. Is key 'Five' Exists?"); if (numbers.containsKey("Five")) { System.out.println("YES - Value is : " + numbers.get("Five")); } else { System.out.println("NO"); } } }
Output
——————
1. Is key ‘One’ Exists ?
YES – Value is : 1
2. Is key ‘Two’ Exists?
YES – Value is : 2
3. Is key ‘Five’ Exists?
NO
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet