Wednesday, November 12, 2014

Java Code - This returns the first key in a HashMap given a value

Java Code - This returns the first key in a HashMap given a supplied value

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * general purpose utility methods
 * @author ranjit sandhu
 */
public class Utils {

    // gets first hashmap key from supplied value    
    public static String getKeyByValue(LinkedHashMap lhm, String value) {
        String tt = "";
        Iterator fat = lhm.entrySet().iterator();
        while (fat.hasNext()) {
            Map.Entry pairs = (Map.Entry)fat.next();
            String key = pairs.getKey().toString();
            String val = pairs.getValue().toString();
            if (val.equals(value)) {
                tt = key;
            }
        }
        return tt;
    } // end getKeyByValue
    
} // end Utils

1 comment:

  1. sigh...this code is bad and i wrote it...shit...keys are atomic, values can be multiple, this will return the LAST key with the given value :(
    also is a linkedhashmap an ordered list ? i am too lazy to google it.
    i gotta work on this ruby faye crap.

    ReplyDelete