TreeMap containsValue() Method in Java With Examples
Last Updated :
09 Jun, 2022
In Java, containsValue() method of the TreeMap class is used to check whether a particular value is being mapped by any key in the TreeMap. It takes the value as a parameter and returns True if that value is mapped by any of the keys in the map.
--> java.util Package
--> TreeMap class
--> containsValue() Method
Syntax:
Tree_Map.containsValue(Object Value)
Parameters: The value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map. ( Only one parameter)
Return Type: A boolean value, true if the mapping of the value is detected else false.
Note: In java, while returning boolean values are returned as true false only not as 0 and 1 as it is not allowed so do will throw error at compilation.
Example 1: Mapping String Values to Integer Keys.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> tree_map
= new TreeMap<Integer, String>();
tree_map.put( 10 , "Geeks" );
tree_map.put( 15 , "4" );
tree_map.put( 20 , "Geeks" );
tree_map.put( 25 , "Welcomes" );
tree_map.put( 30 , "You" );
System.out.println( "Initial Mappings are: "
+ tree_map);
System.out.println(
"Is the value 'Geeks' present? "
+ tree_map.containsValue( "Geeks" ));
System.out.println(
"Is the value 'World' present? "
+ tree_map.containsValue( "World" ));
}
}
|
Output
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Is the value 'Geeks' present? true
Is the value 'World' present? false
Example 2: Mapping Integer Values to String Keys.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeMap<String, Integer> tree_map
= new TreeMap<String, Integer>();
tree_map.put( "Geeks" , 10 );
tree_map.put( "4" , 15 );
tree_map.put( "Geeks" , 20 );
tree_map.put( "Welcomes" , 25 );
hastree_map_map.put( "You" , 30 );
System.out.println( "Initial Mappings are: "
+ tree_map);
System.out.println( "Is the value '10' present? "
+ tree_map.containsValue( 10 ));
System.out.println( "Is the value '30' present? "
+ tree_map.containsValue( 30 ));
System.out.println( "Is the value '40' present? "
+ tree_map.containsValue( 40 ));
}
}
|
Output:
Note: Similarly the same operation can be performed with any type of Mappings with variation and combination of different data types.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...