如何通过提供值从HashMap获取密钥?

时间:2014-04-30 21:49:35

标签: java hashmap

private static HashMap<Script, String> scripts = new HashMap<>();

    public Script getScriptByName(String name) {
        for (String s : scripts.values()) {
            if (s.equals(name)) {
                ...
            }
        }
        return null;
    }

鉴于此代码,我如何获取特定值的密钥?

1 个答案:

答案 0 :(得分:6)

导航浏览地图的条目:

for (Map.Entry<String, String> entry : scripts.entrySet()) {
    if (entry.getValue().equals(name)) {
        return entry.getKey();
    }
}

return null;