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)可能有多个匹配值。 –