Java 检查 hashmap 中的值是否已经存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23632529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a value in hashmap already exists
提问by Jose Ramon
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
我创建了一个包含字符串值的 hashMap。我希望每次向映射添加新值以检查哈希映射中是否已存在。我已经定义
final HashMap<String, String> map = new HashMap<String, String>();
map.put(key, myURL.toString());
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?
如何遍历哈希图以检查是否存在重复项?
采纳答案by Unihedron
map.containsKey(key)
map.containsKey(key)
map.containsValue(val)
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
指定者:http: //docs.oracle.com/javase/7/docs/api/java/util/Map.html
回答by xxx
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
检查类javadocs,你会看到有两个方法 contains key 和 containsvalue http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
回答by N4zroth
boolean result = selections.values().stream().anyMatch(Boolean::booleanValue);
回答by GhostCat
Simple:
简单的:
return map.containsValue(myURL.toString());
for example. Or, using java8 streams:
例如。或者,使用 java8 流:
return map.values().stream().anyMatch(v -> v.equals(myURL.toString()))
But as you ask for efficientsolutions, I suggest you go with the old-school non stream version. Because the second version is most likely using noticeably more CPU cycles.
但是当您要求有效的解决方案时,我建议您使用老式的非流版本。因为第二个版本很可能使用明显更多的 CPU 周期。
Only if your map has zillionsof entries, and you are looking at response timeonly, then maybe using parallelStream()
could give you the answer more quickly.
只有当您的地图有无数个条目,并且您只关注响应时间时,也许使用parallelStream()
才能更快地为您提供答案。
回答by Nick
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
说到效率,这种数据结构的存在就是低效率和糟糕设计的证明。containsValue(V)
是你正在寻找的方法