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


This Java code defines a class named SearchValue 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 containsValue() method of the TreeMap class is used to check whether the map contains a specific value, in this case, the string value "Charles". If the value is present in the map, the code prints a message indicating that the map contains the value. Otherwise, it prints a message indicating that the map does not contain the value.

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

Source Code

import java.util.*;  
public class SearchValue
{  
	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.containsValue("Charles"))
		{
			System.out.println("TreeMap Contains Value Charles");
		}
		else
		{
			System.out.println("TreeMap does Not Contain Value Charles");
		}
	}
}

Output

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

Example Programs