0
我想在hashmap的幫助下打印密鑰。 Isee解決這些方法,但我找到正確的解決方案if(hashmapOption.containsValue(parent.getItemAtPosition(position).toString()))
。 如果這是真的,則輸出關鍵值。如何使用HashMap中的值幫助打印密鑰android
我想在hashmap的幫助下打印密鑰。 Isee解決這些方法,但我找到正確的解決方案if(hashmapOption.containsValue(parent.getItemAtPosition(position).toString()))
。 如果這是真的,則輸出關鍵值。如何使用HashMap中的值幫助打印密鑰android
您必須iterate all entries,如果包含打印:
// your map is map = HashMap<String, String>
public void printIfContainsValue(Map mp, String value) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
// print if found
if (value.equals(pair.getValue())) {
System.out.println(pair.getKey() + " = " + pair.getValue());
}
it.remove(); // avoids a ConcurrentModificationException
}
}
還是回到了Entry
,做你想要做什麼用:
// your map is map = HashMap<String, String>
public Map.Entry containsValue(Map mp, String value) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
// return if found
if (value.equals(pair.getValue())) {
return pair;
}
it.remove(); // avoids a ConcurrentModificationException
}
return null;
}
注:通過John Skeet爲指向你要知道, :
HashMap
是專爲查找key
,而不是value
;value
。
你的問題是什麼? –
那麼你可以遍歷地圖中的所有條目,檢查值是否匹配,如果是,則打印該鍵。但是:a)緩慢;基本上HashMap被設計用於按鍵查找,而不是值; b)可能有多個匹配值。 –