简体   繁体   中英

How do I get a key from a HashMap by providing the value?

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

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

Given this code, how can I get the key of a specific value?

Navigate through the entries of the map instead:

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

return null;      

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