Java.util.TreeMap.containskey() and containsValue() in Java
Last Updated :
01 Nov, 2017
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.
import java.io.*;
import java.util.*;
public class containsKey {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
treemap.put(2, "two");
treemap.put(7, "seven");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
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
import java.io.*;
import java.util.*;
public class containsValue {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
treemap.put(2, "two");
treemap.put(7, "seven");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
System.out.println(treemap.containsValue("six"));
System.out.println(treemap.containsValue("four"));
}
}
|
Output:
true
false
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...