If you want to check whether the specified value is present in the HashMap or not you can use containsValue()
method in the java.util.Map
which returns true if this map maps one or more keys to the specified value.
Remember that in a Map key must be unique but one or more keys may have the same value.
Syntax of the method is as given below.
containsValue(Object value)
value- Passed parameter is the value whose presence in this map is to be tested.
Method returns true if this map maps one or more keys to the specified value. Returns false if there is no mapping for the specified value.
containsValue() Java example
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 already not there.
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