Pergunta

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?

Foi útil?

Solução 2

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

Outras dicas

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.

map.containsValue method is what you need. See doc

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

boolean result = selections.values().stream().anyMatch(Boolean::booleanValue);

Speaking of efficiency, the existence of this data structure is a proof of inefficiency and bad design. containsValue(V) is the method you're looking for

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top