Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value in hashmap already exists

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?

like image 892
Jose Ramon Avatar asked Nov 28 '22 11:11

Jose Ramon


1 Answers

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.

like image 104
GhostCat Avatar answered Dec 15 '22 02:12

GhostCat