Java TreeMap.containsValue(Object value) example

In this java tutorial, You will learn how to use containsValue(Object value) method of TreeMap class.The containsValue(Object value) method is used to return true if this map, maps one or more keys to the specified 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.

Throws

ClassCastException - if the specified value cannot be compared with the values currently in the map.

NullPointerException - if the specified value is null and this map uses natural ordering, or its comparator does not permit null values.

Java TreeMap containsValue(Object value) example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.containsValue("Pooja"); returns true as "Pooja" is exists in the TreeMap.
  • students.containsValue("Nitin"); returns false as "Nitin" is not exists in the TreeMap.
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);

        System.out.println(students.containsValue("Pooja"));

        System.out.println(students.containsValue("Nitin"));
    }
}

output

TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
true
false