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

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *