5

Possible Duplicate:
Java Hashmap: How to get key from value?

I know that a HashMap contains a particular integer variable as value. How can I get the key associated with this value?

Community
  • 1
  • 1
London guy
  • 27,522
  • 44
  • 121
  • 179

6 Answers6

7

This code will do that:

  public List<Object> getKeysFromValue(Map<?, ?> hm, Object value){
    List <Object>list = new ArrayList<Object>();
    for(Object o:hm.keySet()){
        if(hm.get(o).equals(value)) {
            list.add(o);
        }
    }
    return list;
  }
Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
3

Here you go:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test
{
    public static void main( String args[] )
    {
        Map < Integer , Integer > map = new HashMap < Integer , Integer >();

        map.put( 1 , 2 );
        map.put( 3 , 4 );
        map.put( 5 , 6 );
        map.put( 7 , 4 );

        List< Integer > keys = new ArrayList< Integer >();

        Integer value = 4;

        for ( Integer key : map.keySet() )
        {
            if ( map.get( key ).equals( value ) )
            {
                keys.add( key );
            }
        }

        System.out.println( value + " has been found in the following keys: " + keys );
    }
}

The output is:

4 has been found in the following keys: [7, 3]
Jonathan Payne
  • 2,223
  • 13
  • 11
2
Set<Map.Entry> entries = hashMap.entrySet();
for(Map.Entry entry : entries) {
   if(entry.getValue().equals(givenValue)) {
       return entry.getKey();
   }
}
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
1

Hashmaps help you to find the value if you know the key. IF you really want the key from the value, you will have to iterate through all the items, compare the values, and then get the key.

Kumar Bibek
  • 9,016
  • 2
  • 39
  • 68
0

Loop over the entrySet is faster, because you don't query the map twice for each key.

public Set<Object> getKeysFromValue(Map<Object, Integer> map, int value) {
        Set<Object> keys = new HashSet<Object>();
        for (Map.Entry<Object, Integer> entry:map.entrySet()) {
            //if value != null
            if (entry.getValue() == value) {
                keys.add(entry.getKey());
            }
        }
return keys;
0

Try this....short and sweet way...

HashMap<String, Integer> list = new HashMap<String,Integer>();

        for (Map.Entry<String, Integer> arr : list.entrySet()){


                System.out.println(arr.getKey()+" "+arr.getValue()); 
        }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75