Tuesday 16 June 2015

How to get entry set from HashMap

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

public class HashMapEntrySet {
   
    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");
       
        //print hashmap
        System.out.println("HashMap = "+hm);
       
        Set<Entry<Integer, String>> entry =hm.entrySet();
       
        for (Entry<Integer, String> entry2 : entry) {
            System.out.println(" Key = "+entry2.getKey()+" Value = "+entry2.getValue());
        }
    }

}




Output:

 HashMap = {1=ankush, 2=amit, 3=shivam, 4=ankit, 5=yogesh}

 Key = 1 Value = ankush

 Key = 2 Value = amit
 
 Key = 3 Value = shivam

 Key = 4 Value = ankit

 Key = 5 Value = yogesh

No comments:

Post a Comment