How we can get the list of Key from HashMap?

 

Lets assume in interview you are been asked to list all the values in HashMap. HashMap contains around 1000 values and you have not given the list of keys to get the corresponding values. From HashMap to get the values first you need know the keys and later you can get the list of corresponding values.

            Today we will discuss about how to find the list of Key from HasMap. Before looking into direct program lets see some of the key features of HashMap and different between HashMap and HashTable. HashMap and HashTable will implements Map Interface but there are few difference between both of them where everyone needs to know.

HashMap is not synchronized where as HashTable is synchronized. If one who wants to use HashMap with synchronized then they the synchronize by using Java Collection utility as given below.
Since HashTable is synchronized by default it will slower than HashMap and performance wise HashMap will be better.
HashTable is defined in earlier version before Java Collections introduced.
HashMap will allow null key and value and where as in HashTable you cant place null key or value.
Iterator in HashMap is a fail-fast if any one tries to modify or remove the element from the HashMap and where as Enumeration in HashTable is not such. 
In HashMap value or key order will not be guarantee that will be same as inserted.

   

public class MyKeyList {
       
       public static void main(String[] args) {
               HashMap<String, String> hm = new MyKeyList().getHashMap();
                    
               Set<String> set = (Set<String>)hm.keySet();
               Iterator<String> itr = set.iterator();
               while(itr.hasNext()){
                       System.out.println(itr.next());
               }
               
               // Other way just by for loop as 
               for(Object key : hm.keySet()){
   System.out.println(hm.get(key));
  }

       }
       
       private HashMap<String, String> getHashMap(){
               HashMap<String, String> hm = new HashMap<String, String>();
               hm.put("one", "java");
               hm.put("four", ".NET");
               hm.put("two", "C");
               hm.put("five", "PHP");
               hm.put("three", "C++");
               return hm;
       }        
}


      In above program we have saved 5 values in HashMap and its been returned to main method and we have used Set and Iterator to get keys from the HashMap.
      Here need to remember about the function called ketSet() used to get the set of Keys from HashMap.



OUTPUT:



one
two
five
three
four



Hope you are clear now how to get list of Key from HashMap. You have any comments please drop it down.







No comments:
Write comments