简体   繁体   中英

How to print key with the help of value in hashmap in android

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

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:

  1. that's slow; basically HashMap is designed for lookup by key , not value ;
  2. there may be multiple matching values , this methods will only return first found value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM