I want to print key with the help of hashmap. Isee solution these method but i find right solutionif(hashmapOption.containsValue(parent.getItemAtPosition(position).toString()))
.
if this is true than print the key value.
Asked
Active
Viewed 775 times
0

Anand Jain
- 2,365
- 7
- 40
- 66
-
What is your question? – ρяσѕρєя K Nov 18 '15 at 10:18
-
3Well you can iterate through all the entries in the map, check whether the value matches and print the key if so. But: a) that's slow; basically HashMap is designed for lookup by key, not value; b) there may be multiple matching values. – Jon Skeet Nov 18 '15 at 10:18
1 Answers
2
You must iterate all entries and print if containing:
// 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
}
}
Or return the Entry
and do what you want with it:
// 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;
}
NOTE: as pointed by John Skeet you must know that:
- that's slow; basically
HashMap
is designed for lookup bykey
, notvalue
; - there may be multiple matching values, this methods will only return first found
value
.

Community
- 1
- 1

Jordi Castilla
- 26,609
- 8
- 70
- 109