문제

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?

도움이 되었습니까?

해결책 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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top