开发者

How to create a method to get the Key of a value(string) in a hashmap

开发者 https://www.devze.com 2023-02-10 23:18 出处:网络
I have an assignment, This is my HashMap initialization.. I can only use standard JAVA API. private static HashMap<String, HashSet<String>> hMap = new HashMap<String, HashSet<String

I have an assignment, This is my HashMap initialization.. I can only use standard JAVA API.

private static HashMap<String, HashSet<String>> hMap = new HashMap<String, HashSet<String>>();

Is it possible to get the Key of a specified value say getkey(hMap,"today") and it would return the key where today is located..

As开发者_如何学Golo is there a way to get the last value of a Key in my HashSet?

Any help is appreciated thanks!


But actually you can have more than one keys which has "today". So I return List.toString with keys

private static HashMap<String, HashSet<String>> hMap = new HashMap<String, HashSet<String>>();

public static String getKey(Map<String, HashSet<String>> map, String value) {
    List<String> returnKey = new ArrayList<String>();

    for (String s : map.keySet()) {
        if (map.get(s).contains(value)) {
            returnKey.add(s);
        }
    }

    return returnKey.toString();

}

public static void main(String[] args) {
    // put sth to hMap
    System.out.println(getKey(hMap, "today"));
}


What you really want is Google's Guava BiMap.

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

If you can't use that, then you're going to have to loop through the maps entry items looking for a match which isn't overly speedy.


As generically as possible with nothing but a Map.

public static <K,V> K getKey(Map<K,V> map,V val){
    for(Map.Entry<K,V> entry:map.entrySet()){
        if(entry.getValue().equals(val)){
            return entry.getKey();
        }
    }
    return null;
}

This will only return the key of the first value that matches. If you want to return all the keys for a specific value, then you can modify this method to accumulate they keys into a List and return that instead.

(Don't get your hopes up for a speedy retrieval...)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号