Friday, 1 August 2014

Get key from value in HashMap


import java.util.*;

public class GetKeyFromValue {
    public static void main(String args[]){
        HashMap<Integer, String> map = new HashMap<> ();
        
        /* Add Elements to map*/
        map.put(1, "Krishna");
        map.put(2, "Arjun");
        map.put(3, "Murali");
        map.put(4, "Krishna");
        map.put(5, "Joel");
        
        Set<HashMap.Entry<Integer, String>> set = map.entrySet();
        Iterator<HashMap.Entry<Integer, String>> iter = set.iterator();
        
        String searchVal = "Krishna";
        
        System.out.println("Keys with respect to value " + searchVal);
        while(iter.hasNext()){
           HashMap.Entry entry = iter.next();
           if(entry.getValue().equals(searchVal)){
               System.out.println(entry.getKey());
           }
        }
    }
}

Output
Keys with respect to value Krishna
1
4




                                                             Home

No comments:

Post a Comment