有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建一个方法来获取hashmap中的值(字符串)的键

我有一个任务,这是我的HashMap初始化。。我只能使用标准的JavaAPI

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

是否可以获取指定值的键,比如getkey(hMap,“today”),然后返回today所在的键

还有,有没有一种方法可以获取哈希集中某个键的最后一个值

感谢您的帮助,谢谢


共 (3) 个答案

  1. # 1 楼答案

    你真正想要的是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.

    如果你不能使用它,那么你将不得不在地图条目中循环寻找一个速度不太快的匹配项

  2. # 2 楼答案

    尽可能一般地只使用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;
    }
    

    这将只返回匹配的第一个值的键。如果要返回特定值的所有键,可以修改此方法,将它们累积到List中,然后返回该值

    (不要对快速检索抱太大希望…)

  3. # 3 楼答案

    但实际上你可以有不止一把钥匙,上面写着“今天”。所以我返回列表。摆弄钥匙

    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"));
    }