In this shot, we will learn how to use the TreeMap.containsValue()
method in Java, which is present in the TreeMap
class inside the java.util
package.
The TreeMap.containsValue()
method is used to check whether a particular value is being mapped by any of the keys present in the TreeMap
.
The syntax of the TreeMap.containsValue()
method is shown below:
boolean containsValue(Object value)
Here, the value is of the type Object
, as every class is a subclass of the Object
class.
The TreeMap.contains value()
method accepts only one parameter, i.e., the value which needs to be checked to see whether it is mapped with any keys in the TreeMap
or not.
The TreeMap.containsValue()
returns a boolean value:
True
: If the value is mapped with any key present in the TreeMap
.False
: If the value is not mapped with any key present in the TreeMap
.This method can be applied to any mapping with combinations of different data types.
Let’s have a look at some examples.
<Integer, String>
In this example, we map string values to integer keys. However, this method can be applied to any mapping with combinations of different data types.
// importing required packageimport java.util.*;// Main classclass Main{// main driver functionpublic static void main(String[] args){// creating an empty TreeMapTreeMap<Integer, String> t1 = new TreeMap<Integer, String>();// inserting values in the TreeMapt1.put(1, "Educative");t1.put(5, "Python");t1.put(2, "Java");t1.put(27, "Learn Coding");t1.put(9, "C++");// checking for values in the TreeMapSystem.out.println("Value = Python in TreeMap? " + t1.containsValue("Python"));System.out.println("Value = Javascript in TreeMap? " + t1.containsValue("Javascript"));System.out.println("Value = C++ in TreeMap? " + t1.containsValue("C++"));}}
Main
class.main()
function.TreeMap
consisting of keys of type Integer
and values of type String
.TreeMap
by using the TreeMap.put()
method.TreeMap
, or not, with a message.<String, Integer>
In this example, we map integer values to string keys.
// importing required packageimport java.util.*;// Main classclass Main{// main driver functionpublic static void main(String[] args){// creating an empty TreeMapTreeMap<String, Integer> t1 = new TreeMap<String, Integer>();// inserting values in the TreeMapt1.put("Educative", 1);t1.put("Python", 2);t1.put("Java", 3);t1.put("Learn Coding", 4);t1.put("C++", 5);// checking for values in the TreeMapSystem.out.println("Value = 1 in TreeMap? " + t1.containsValue(1));System.out.println("Value = 10 in TreeMap? " + t1.containsValue(10));System.out.println("Value = 3 in TreeMap? " + t1.containsValue(3));}}
Main
class.main()
function.TreeMap
consisting of keys of type String
and values of type Integer
.TreeMap
by using the TreeMap.put()
method.TreeMap
, or not, with a message.So, that is how to use the TreeMap.containsValue()
method in Java to check if a particular value is being mapped by any of the keys present in the TreeMap
, or not.