Write a Java program to test if a map contains a mapping for the specified value


The program uses a HashMap object which has a mapping between integer keys and string values. The containsValue method is used to check if a particular value exists in the map. In the first case, the program checks if the value "Orange" exists in the map, which it does, so the output is "Yes!". In the second case, the program checks if the value "White" exists in the map, which it does not, so the output is "No!".

Source Code

import java.util.*;  
public class TestValue_Contains
{  
	public static void main(String args[])
	{
		HashMap <Integer, String> hash_map = new HashMap <Integer, String> ();
		hash_map.put(1, "Red");
		hash_map.put(2, "Yellow");
		hash_map.put(3, "Black");
		hash_map.put(4, "Pink");
		hash_map.put(5, "Orange");
		hash_map.put(6, "Blue");
 
		System.out.println("HashMap : " + hash_map);
		System.out.println("1. Is value \'Orange\' Exists ?");
		if (hash_map.containsValue("Orange"))
		{
			System.out.println("Yes! ");
		}
		else
		{
			System.out.println("no!");
		}
 
		System.out.println("\n2. Is value \'White\' Exists ?");
		if (hash_map.containsValue("White"))
		{
			System.out.println("yes! - " );
		} 
		else
		{
			System.out.println("No!");
		}
	}
}

Output

HashMap : {1=Red, 2=Yellow, 3=Black, 4=Pink, 5=Orange, 6=Blue}
1. Is value 'Orange' Exists ?
Yes!

2. Is value 'White' Exists ?
No!