简体   繁体   中英

Retrieve key from HashMap

How to retrieve index of a map using key value?

I have a map with string as key and int as value. I will pass map and key value to a method,in that method based on the index of the passed key value it will return either true or false. I need this util method for my application.

package sample;

import java.util.HashMap;
import java.util.Map;

public class MAp {
    public static void main(String args[]) {
        Map<String, Integer> sampleMap = new HashMap<String, Integer>();
        sampleMap.put("ABC", 12);
        sampleMap.put("DEF", 13);
        boolean flag = canAllocate("ABC", sampleMap);
    }

    private static boolean canAllocate(String string, Map<String, Integer> sampleMap) {
        if (sampleMap.containsKey("ABC")) {
            int index = 0;
            // I need to get index of "ABC" in map;
            if (index == 0) {
                return true;
            }
        }
        return false;
    }
}

I would suggest you try using a LinkedHashMap , which will preserve the order, then do as Mena suggested. Otherwise, the 'order' doesn't mean much.

You could just iterate the keySet and increment an int .

index i = 0;
for (String key: sampleMap.keySet()) {
    if (key.equals(myString)) {
        return i;
    }
    else {
        i++;
    }
}
return -1;

To be noted, there is no indexing as such in the key set, so the whole functionality seems to have little value.

" // I need to get index of "ABC" in map "

It has no sense to do that, "ABC" itself is a sort of index ine the MAP. Key -> Map

Index -> Array/List

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