TreeMap containsValue(Object value) method in java

Let’s learn TreeMap containsValue(Object value) method in java.

TreeMap containsValue(Object value) method in java

containsValue(Object value) returns true if this map maps one or more keys to the specified value.

Syntax:

public boolean containsValue(Object value)

Parameters:

value value whose presence in this map is to be tested.

Returns:

true if a mapping to value exists; false otherwise.

Now let’s see example on TreeMap containsValue(Object value) method.

import java.util.TreeMap;
public class TreeMapContainsValueMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      // Map string values to integer keys
      tm.put(16, "indigo");
      tm.put(12, "red");
      tm.put(14, "indigo");
      tm.put(18, "orange");
      tm.put(20, "violet");
      System.out.println("TreeMap before using containsValue() method: " + tm);
      // checking for Value 'indigo'
      System.out.println("Does value 'indigo' present? " + tm.containsValue("indigo"));
      // checking for Value 'blue'
      System.out.println("Does value 'blue' present? " + tm.containsValue("blue"));
   }
}

Output:

TreeMap before using containsValue() method: {12=red, 14=indigo, 16=indigo, 18=orange, 20=violet}
Does value ‘indigo’ present? true
Does value ‘blue’ present? false


Now let’s map Integer values to String keys.

import java.util.TreeMap;
public class TreeMapContainsValueMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      // Map integer values to string keys
      tm.put("indigo", 16);
      tm.put("red", 12);
      tm.put("indigo", 14);
      tm.put("orange", 18);
      tm.put("violet", 20);
      System.out.println("TreeMap before using containsValue() method: " + tm);
      // Checking for the Value '12'
      System.out.println("Does value '12' present? " + tm.containsValue(12));
      // Checking for the Value '14'
      System.out.println("Does value '14' present? " + tm.containsValue(14));
      // Checking for the Value '20'
      System.out.println("Does value '20' present? " + tm.containsValue(20));
   }
}

Output:

TreeMap before using containsValue() method: {indigo=14, orange=18, red=12, violet=20}
Does value ’12’ present? true
Does value ’14’ present? true
Does value ’20’ present? true


Also read – interface in java