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?
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?
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;
}
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]
Set<Map.Entry> entries = hashMap.entrySet();
for(Map.Entry entry : entries) {
if(entry.getValue().equals(givenValue)) {
return entry.getKey();
}
}
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.
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;
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());
}