Search This Blog

Sunday, 7 December 2014

How to Add and Retrive Data from the Map in Java


import java.util.Iterator;
import java.util.Map;
import java.util.Set;

class SimpleMapProgram{
    public static void main(String[] args){
 //creating the map object of key as integer and value as String type
 
 Map<Integer,String> map=new HashMap<Integer,String>();
//adding the element into map there is put() method in java for adding the element into the Map
map.put(1,"Core Java");//1 st element added into the HashMap
map.put(2,"Adv Java");//2 st element added into the HashMap
map.put(3,"Spring");//3 st element added into the HashMap
map.put(4,""Hibernate);//4 st element added into the HashMap
map.put(5,"Struts");//5 st element added into the HashMap

//retriving the element from the Hashmap
//first the give set type object for getting the all keys of the HashMap       
       Set keyset=map.keySet();
       //here getting the Iterator object for retriving the hashmap object
 Iterator<Integer> it=keyset.iterator();

      System.out.println("HashMap Element Are As Follow");
        while(it.hasNext()){
        //getting the key
            int key=it.next();
         //getting the value of the element by passing the key as argument to the get method
            String value=map.get(key);
         //printing the key and value of the object
            System.out.println(key+"-----------"+value);
        } //while loop closed
      }//main method close
}//class close




Output:


HashMap Element Are As Follow
                       1---------Core Java
                       2---------Adv Java
                       3---------Spring
                       4---------Hibernate
                       5---------Struts

No comments:

Post a Comment