[英]Check if a value already exists in a hashmap, and allow the user to enter a valid value if it does
[英]Check if a value in hashmap already exists
我創建了一個包含String值的hashMap。 我想每次添加一個新值來映射以檢查hashmap中是否已存在。 我已經定義了
final HashMap<String, String> map = new HashMap<String, String>(); map.put(key, myURL.toString());
我怎么能循環遍歷hashmap來檢查是否存在重復?
簡單:
return map.containsValue(myURL.toString());
例如。 或者,使用java8流:
return map.values().stream().anyMatch(v -> v.equals(myURL.toString()))
但是當你要求有效的解決方案時,我建議你選擇老式的非流式版本。 因為第二個版本最有可能使用明顯更多的CPU周期。
只有當你的地圖有數以萬計的條目,並且你只關注響應時間時 ,那么使用parallelStream()
可以更快地給你答案。
map.containsKey(key)
map.containsValue(val)
如果你堅持迭代,請執行:
Iterator<Entry<String, String>>iterator=map.entrySet();
while(iterator.hasNext()){
final Entry<String, String>next=iterator.next();
next.getKey(); next.getValue();
}
指定人: http : //docs.oracle.com/javase/7/docs/api/java/util/Map.html
map.containsValue
方法就是你所需要的。 見文檔
檢查類javadocs,你會看到有兩個方法包含key和containsvalue http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
boolean result = selections.values().stream().anyMatch(Boolean::booleanValue);
說到效率,這種數據結構的存在是低效率和糟糕設計的證明。 containsValue(V)
是您正在尋找的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.