Check if a value in hashmap already exists
Solution 1
map.containsKey(key)
map.containsValue(val)
If you insist on iterating, do:
Iterator<Entry<String, String>>iterator=map.entrySet();
while(iterator.hasNext()){
final Entry<String, String>next=iterator.next();
next.getKey(); next.getValue();
}
Specified by: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Solution 2
Simple:
return map.containsValue(myURL.toString());
for example. Or, using java8 streams:
return map.values().stream().anyMatch(v -> v.equals(myURL.toString()))
But as you ask for efficient solutions, I suggest you go with the old-school non stream version. Because the second version is most likely using noticeably more CPU cycles.
Only if your map has zillions of entries, and you are looking at response time only, then maybe using parallelStream()
could give you the answer more quickly.
Solution 3
map.containsValue
method is what you need. See doc
Solution 4
boolean result = selections.values().stream().anyMatch(Boolean::booleanValue);
Solution 5
Check the class javadocs, you'll see that there are two methods contains key and containsvalue http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
![Jose Ramon](https://i.stack.imgur.com/uley8.jpg?s=256&g=1)
Jose Ramon
Updated on August 29, 2020Comments
-
Jose Ramon almost 4 years
I ve created a hashMap which contains String values. I want every time that I add a new value to map to check if already exists in hashmap. I have defined
final HashMap<String, String> map = new HashMap<String, String>(); map.put(key, myURL.toString());
How could I loop through the hashmap to check if a duplicate exist?