Write a Java program to check whether a HashMap contains a specified Key or not


First, a HashMap is created and some key-value pairs are added to it using the put() method. In this case, the keys are integers and the values are strings representing names.

Then, the containsKey() method of the HashMap is used to check if the key 105 is present in the HashMap or not. If the key is present, the program prints the message "Key 105 is contained in 'stu' HashMap". Otherwise, it prints the message "Key 105 is not contained in 'stu' HashMap".

In this case, the output will be "Key 105 is contained in 'stu' HashMap", since the key 105 was added to the HashMap earlier.

Source Code

import java.util.*;
public class Specified_KeyNot
{
	public static void main(String[] args)
	{
		HashMap < Integer, String > stu = new HashMap < > ();
		stu.put(101, "Kim");
		stu.put(102, "Arun");
		stu.put(103, "Deepika");
		stu.put(105, "Joes");
		stu.put(107, "John");
		stu.put(108, "Vijay");
 
		if (stu.containsKey(105))
		{
			System.out.println("Key 105 is contained in 'stu' HashMap");
		}
		else
		{
			System.out.println("Key 105 is not contained in 'stu' HashMap");
		}
	}
}

Output

Key 105 is contained in 'stu' HashMap