Write a Java program to search a key in a Tree Map


This Java code defines a class named SearchKey which contains a main method that creates a TreeMap object named s1 and adds five key-value pairs to it. The keys are integers and the values are strings representing the names of individuals. The keys are inserted in ascending order from 10 to 50.

The code then prints the contents of the TreeMap object to the console. Next, the containsKey() method of the TreeMap class is used to check whether the map contains a specific key, in this case, the integer value 30. If the key is present in the map, the code prints a message indicating that the map contains the key. Otherwise, it prints a message indicating that the map does not contain the key.

This code demonstrates how to search for a key in a TreeMap using the containsKey() method, which returns true if the map contains the specified key and false otherwise.

Source Code

import java.util.*;  
public class SearchKey
{  
	public static void main(String args[])
	{
		TreeMap<Integer,String> s1 = new TreeMap<Integer,String>();		
		s1.put(10, "John");
		s1.put(20, "Joes");
		s1.put(30, "Smith");
		s1.put(40, "Charles");
		s1.put(50, "George");
		System.out.println("TreeMap 1 : "+s1);
 
		if(s1.containsKey(30))
		{
			System.out.println("TreeMap Contains Key 30");
		}
		else
		{
			System.out.println("TreeMap does Not Contain Key 30");
		}
	}
}

Output

TreeMap 1 : {10=John, 20=Joes, 30=Smith, 40=Charles, 50=George}
TreeMap Contains Key 30

Example Programs