[Snip] Get the key of a value in your map

Discussion in 'Resources' started by r3Fuze, Dec 19, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    r3Fuze

    I found this little snippet of code to be VERY useful. What it does is getting the key of the value you put in.

    Exmaple:
    Code:java
    1. HashMap<String, Integer> map = new HashMap<String, Integer>();
    2. map.put("one", 1);
    3. map.put("two", 2);
    4.  
    5. System.out.println(getKeyByValue(map, 2)); // Returns "two"
    6. System.out.println(getKeyByValue(map, 1)); // Returns "one"


    The code:
    Code:java
    1. public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    2. for (Entry<T, E> entry : map.entrySet()) {
    3. if (value.equals(entry.getValue())) { return entry.getKey(); }
    4. }
    5. return null;
    6. }
     
    DrAgonmoray likes this.
  2. Offline

    ferrybig

    does it works on maps that allow null as bvalues, or would it throw a NullPointerException?
     
  3. Offline

    Pandemoneus

    Sadly, your code only gets the first key it finds for a value, so it's not possible to get all keys if you have the same value a few times.
     
Thread Status:
Not open for further replies.

Share This Page