There are two variants of contains() in Java.util.TreeMap, both are discussed in this article.
1. containskey(Object o) : It returns true if the map contains a mapping for the specified key.
Parameters: o : The key which will be tested whether present or not. Return Value: Returns true if there is a mapping for the given key. Exception: ClassCastException : This is thrown if the given key cannot be compared with the keys currently in the map. NullPointerException : This is thrown if the specified key is null.
// Java code to demonstrate the working // of containsKey() import java.io.*; import java.util.*; public class containsKey { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // assigning the values in the tree map // using put() treemap.put( 2 , "two" ); treemap.put( 7 , "seven" ); treemap.put( 3 , "three" ); treemap.put( 6 , "six" ); treemap.put( 9 , "nine" ); // Use of containsKey // returns true if mapping for the number is present System.out.println(treemap.containsKey( 6 )); System.out.println(treemap.containsKey( 4 )); } } |
Output:
true false
2. containsValue(Object o) : It returns true if this map maps one or more keys to the specified value.
Parameters: o : This is the value whose presence in this map is to be tested. Return Value: Returns true if a mapping to this value exists else false. Exception: NA
// Java code to demonstrate the working // of containsValue() import java.io.*; import java.util.*; public class containsValue { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // assigning the values in the tree map // using put() treemap.put( 2 , "two" ); treemap.put( 7 , "seven" ); treemap.put( 3 , "three" ); treemap.put( 6 , "six" ); treemap.put( 9 , "nine" ); // Use of containsValue // returns true if more than one keys are mapped System.out.println(treemap.containsValue( "six" )); System.out.println(treemap.containsValue( "four" )); } } |
Output:
true false
This article is contributed by Shambhavi Singh. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.