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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With