سؤال

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;      
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top