Java Utility Library

Java TreeMap - containsValue() Method



The java.util.TreeMap.containsValue() method returns true if this map contains one or more keys mapped to the specified value.

Syntax

public boolean containsValue(Object value)

Parameters

value Specify the value whose presence in this map is to be tested

Return Value

Returns true if this map contains one or more keys mapped to the specified value.

Exception

NA.

Example:

In the example below, the java.util.TreeMap.containsValue() method is used to check whether the map contains any key which is mapped to the specified value or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating MyMap
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");

    //check for value - "Kim"
    System.out.print("Does MyMap contain key(s) mapped to 'Kim'? - ");  
    System.out.print(MyMap.containsValue("Kim"));  
    //check for value - "Sam"
    System.out.print("\nDoes MyMap contain key(s) mapped to 'Sam'? - ");  
    System.out.print(MyMap.containsValue("Sam"));  
  }
}

The output of the above code will be:

Does MyMap contain key(s) mapped to 'Kim'? - true
Does MyMap contain key(s) mapped to 'Sam'? - false

❮ Java.util - TreeMap