In Java, the java.util.Map interface provides the method containsValue(Object value) to determine whether a given value is present in the map. This method returns true if one or more keys in the map are associated with the specified value, and false otherwise.
It’s important to note that in a Java Map, keys must be unique, but multiple keys can point to the same value. This makes containsValue() especially useful when you want to verify if a particular value is stored in the map, regardless of which key maps to it.
Syntax of the method is as given below.
boolean containsValue(Object value)
value- Passed parameter is the value whose presence in this map is to be tested.
returns – true if the map contains one or more mappings to the specified value, otherwise false.
Example: Using containsValue() in Java
1. Here we have a map with few key, value pairs. We want to check if the specified value is already there or not using containsValue() method.
import java.util.HashMap;
import java.util.Map;
public class ContainsValueDemo {
public static void main(String[] args) {
// creating HashMap
Map<String, String> langMap = new HashMap<String, String>();
langMap.put("ENG", "English");
langMap.put("NLD", "Dutch");
langMap.put("ZHO", "Chinese");
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
boolean isExistingMapping = langMap.containsValue("Dutch");
System.out.println("Dutch is there in the Map-- " + isExistingMapping);
isExistingMapping = langMap.containsValue("Tamil");
System.out.println("Tamil is there in the Map-- " + isExistingMapping);
}
}
Output
Dutch is there in the Map-- true Tamil is there in the Map-- false
2. You can also use containsValue() method to add a new entry to the Map after checking that the value is not there already.
import java.util.HashMap;
import java.util.Map;
public class ContainsValueDemo {
public static void main(String[] args) {
// creating HashMap
Map<String, String> langMap = new HashMap<String, String>();
langMap.put("ENG", "English");
langMap.put("NLD", "Dutch");
langMap.put("ZHO", "Chinese");
langMap.put("BEN", "Bengali");
langMap.put("ZUL", "Zulu");
if(!langMap.containsValue("Tamil")) {
langMap.put("TAM", "Tamil");
}else {
System.out.println("Value already there in the Map");
}
System.out.println("Language Map-- " + langMap);
}
}
Output
Language Map-- {ZHO=Chinese, ZUL=Zulu, TAM=Tamil, NLD=Dutch, BEN=Bengali, ENG=English}
That's all for this topic Java Map containsValue() - Check if Value Exists in Map. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment