0
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?

kbz
  • 984
  • 2
  • 12
  • 30
  • 3
    If you need to do this, you should probably restructure your data. Perhaps point the map in the other direction? – user2357112 Apr 30 '14 at 21:51
  • 3
    Does it have to be a hashmap? See this answer: http://stackoverflow.com/questions/10699492/bi-directional-map-in-java – Daniel Kaplan Apr 30 '14 at 21:51
  • 1
    possible duplicate of [Java Hashmap: How to get key from value?](http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value) – Brian Roach Apr 30 '14 at 22:01

1 Answers1

6

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;      
VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332