Get a key from value with an HashMap

From CodeCodex

Implementations[edit]

Java[edit]

[Java 5]

public static Object getKeyFromValue(HashMap hm,Object value){
    for(Object o:hm.keySet()){
        if(hm.get(o).equals(value)) {
            return o;
        }
    }
    return null;
}

[Java 1.4]

public static Object getKeyFromValue(HashMap hm,Object value){
    Set ref = hm.keySet();
    Iterator it = ref.iterator();

    while (it.hasNext()) {
        Object o = it.next();
        if(o.equals(value)) {
            return o;
        }
    }
    return null;
}

Ruby[edit]

class Hash
  def get_key(val)
    each do |key, value|
      return key  if value == val
    end
    nil
  end
end

Since version 1.9, builds in method "key" can be used.

key = hash.key(val)