Syntax :
public boolean containsValue(Object value) : According to Oracle docs, returns true if the Map maps one or more keys to the specified value.
Check if a particular value exists in HashMap Example :
Here we have a HashMap of Integer keys and String values, we are checking whether any of the key in HashMap mapped to a particular String value.
import java.util.*; public class ExampleToCheckValue { public static void main(String args[]) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Apple"); hashmap.put(22,"Banana"); hashmap.put(33,"Mango"); hashmap.put(44,"Pear"); hashmap.put(55,"PineApple"); // Checking Value Existence boolean flag = hashmap.containsValue("Mango"); System.out.println("String Mango exists in HashMap? : " + flag); boolean flag2 = hashmap.containsValue("Grapes"); System.out.println("String Grapes exists in HashMap? : " + flag2); } }
Output
String Mango exists in HashMap? : true String Grapes exists in HashMap? : false