Home  >  Core Java

How to Iterate Map in Java

By Arvind Rai, June 09, 2013
In java the object of Map can be iterated in many ways. First way to iterate Map is using Map.entrySet and Map.Entry. Second way to iterate Map is using Map.entrySet and Iterator. Third Way to Iterate Map is using Set and Map.entrySet. Fourth Way to iterate Map is using Map.keySet and values of Map can be iterated by Map.values.
IterateHashMap.java
package com.concretepage.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class IterateHashMap {
    public static void main(String[] args) {
        Map<Integer,Bean> map = new HashMap<Integer,Bean>();
        Bean b1 = new Bean("A");
        Bean b2 = new Bean("B");
        Bean b3 = new Bean("C");
        map.put(1, b1);
        map.put(2, b2);
        map.put(3, b3);
        //first way to iterate Map using Map.entrySet and Map.Entry 
        for(Map.Entry<Integer,Bean> mapEntry : map.entrySet() ){
            System.out.println(mapEntry.getKey() +" "+mapEntry.getValue().name);
        }
        //Second way to iterate Map using Map.entrySet and Iterator 
        Iterator<Map.Entry<Integer,Bean>>  mapEntryIte = map.entrySet().iterator();
        while(mapEntryIte.hasNext()){
            Entry<Integer,Bean> entry = mapEntryIte.next();
            System.out.println(entry.getKey()+" "+entry.getValue().name);
        }
        //Third Way to Iterate Map using Set and Map.entrySet
        Set<Entry<Integer,Bean>> entrySet = map.entrySet();
        for(Entry<Integer,Bean> ent : entrySet){
            System.out.println(ent.getKey()+" "+ent.getValue().name);
        }
        //Fourth Way to iterate Map using Map.keySet
        for(Integer key: map.keySet()){
            System.out.println(key +" "+map.get(key).name);
        }
        //Iterate over Map Value using Map.values
        for(Bean b: map.values()){
            System.out.println(b.name);
        }
    }
}
class Bean {
    public String name;
    public Bean(String name) {
        this.name = name;
    }
 }
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us