Thursday, January 31, 2013

Various Ways to iterate/loop over Map in JAVA

package in.ibm;

import java.util.*;
import java.util.Map.*;

public class MapTest {

    public static void main(String[] args) {
       
   
    Map<String, Integer> m1=new HashMap<String, Integer>();
    m1.put("Sushil",100);
    m1.put("Subhojit", 90);
    m1.put("Manoj", 30);
    m1.put("Kumar", 80);

//1. --------------------------------------------------------------------------------   
    System.out.println("Using keySet() method and Enhanced For Loop");
   
    Set<String> key=m1.keySet();
    for (String k : key) {
        System.out.println(m1.get(k));
   }
  

//2. --------------------------------------------------------------------------------
    System.out.println("Using keySet() method and Iterator");
    Iterator it=key.iterator();
    while(it.hasNext()){
        String k=(String)it.next();
        System.out.println("Key :" +k +" Value: " + m1.get(k));
    }

    //3.--------------------------------------------------------------------------------


    Collection value=m1.values();

    System.out.println("Using values() method");
   
    for (Object object : value) {
        System.out.println("-------------" + object);
    }
  
    //4.--------------------------------------------------------------------------------

    System.out.println("Using toArray() method of collection");

    Object[] arr=value.toArray();
    for (Object object : arr) {
        System.out.println(object);
    }
   
    Set<Map.Entry<String, Integer>> ent=m1.entrySet();
   
//6.--------------------------------------------------------------------------------
    System.out.println("Using entrySet() method and Itrator loop");
   
    Iterator it1=ent.iterator();
    while(it1.hasNext()){
        Entry e=(Map.Entry<String, Integer>)it1.next();
        System.out.println("Key :" + e.getKey() + "   Value: "+ e.getValue() );
        if((Integer)e.getValue()==100)
            it1.remove();
    }
   
   
   
    System.out.println("Using entrySet() method and enhanced for loop");
    //5.--------------------------------------------------------------------------------
   
   
    for(Entry e:ent){
        System.out.println("Key :" + e.getKey() + "   Value: "+ e.getValue() );
     }
   
    //6.--------------------------------------------------------------------------------
    System.out.println("removing element from list using iterator");
   
    Iterator it2=ent.iterator();
    while(it2.hasNext()){
        Entry e=(Map.Entry<String, Integer>)it2.next();
        System.out.println("Key :" + e.getKey() + "   Value: "+ e.getValue() );
        if((Integer)e.getValue()==100)
            it1.remove();  //to show you the remove() method of iterator
    }
   
    }
   
}

No comments: