Showing posts with label java hashmap. Show all posts
Showing posts with label java hashmap. Show all posts

Sunday, 14 June 2015

How to get value of key in HashMap

import java.util.HashMap;
import java.util.Map;

public class HashMapGetValueOfkey {
    public static void main(String[] args) {
       
    Map<Integer,String> hm = new HashMap<Integer,String>();
       
    /*
     * Associates the specified value with the specified key in
       this map (optional operation). If the map previously
       contained a mapping for the key, the old value is
       replaced by the specified value
     */
        hm.put(1,"ankush");
        hm.put(2, "amit");
        hm.put(3,"shivam");
        hm.put(4,"ankit");
        hm.put(5, "yogesh");
       
        /*
         * Returns the value to which the specified
         * key is mapped, or null if this map contains
         *  no mapping for the key.
         */
       
        System.out.println(" key = 1 and value = "+hm.get(1));
        System.out.println(" key = 1 and value = "+hm.get(10));
       
        System.out.println(" key = 1 and value = "+hm.get(5));
        System.out.println(" key = 1 and value = "+hm.get(4));
       
    }

}

Output:

 key = 1 and value = ankush

 key = 1 and value = null

 key = 1 and value = yogesh

 key = 1 and value = ankit


How to iterate through HashMap



import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapIterate {
   
    public static void main(String[] args) {
       
    Map<Integer,String> hm = new HashMap<Integer,String>();
       
    /*
     * Associates the specified value with the specified key in
       this map (optional operation). If the map previously
       contained a mapping for the key, the old value is
       replaced by the specified value
     */
        hm.put(1,"ankush");
        hm.put(2, "amit");
        hm.put(3,"shivam");
        hm.put(4,"ankit");
        hm.put(5, "yogesh");
       
       Set<Integer> keys = hm.keySet();
      
       for (Integer key : keys) {
        System.out.println("key ="+key+" value = "+hm.get(key));
    }
       
       
    }
   

}


Output:

key =1 value = ankush

key =2 value = amit

key =3 value = shivam

key =4 value = ankit

key =5 value = yogesh