PUB ID

Saturday, 4 March 2017

Different Ways To Iterate Map In JAVA......?

package in.blogspot.myjavadoubts

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

public class DifferentWaysToIterateMap {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<Integer, String>(); //create new Instance For Map
      
        //inserting elements into Map
        map.put(0, "Sunday");
        map.put(1, "Monday");
        map.put(2, "Tuesday");
        map.put(3, "Wednesday");
        map.put(4, "Thursday");
        map.put(5, "Friday");
        map.put(6, "Saturday");

        //1-way to Iterate Map
        Iterator<Entry<Integer,String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iterator.next();
            System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
        }
      
        // 2-Way to Iterate Map
        for (Object key : map.keySet()) {
            System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
        }

        // 3-way to Iterate Map -->recomended way to Iterate Map
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }

        //4-Way to Iterate Map-->supports java 8 Only
        map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
    }

}

1 comment: