In this example we are checking whether a particular value exists in HashMap or not. We will be using containsValue() method of HashMap class to perform this check:
public boolean containsValue(Object value)
: Returns true if this map maps one or more keys to the specified value.
Complete Code:
Here we have a HashMap of integer keys and String values, we are checking whether a particular String is mapped to any of the key of HashMap.
import java.util.HashMap; public class CheckValueExample { 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,"Chaitanya"); hashmap.put(22,"Pratap"); hashmap.put(33,"Singh"); hashmap.put(44,"Rajesh"); hashmap.put(55,"Kate"); // Checking Value Existence boolean flag = hashmap.containsValue("Singh"); System.out.println("String Singh exists in HashMap? : " + flag); } }
Output:
String Singh exists in HashMap? : true
Leave a Reply