How to Iterate Map key and value

 

We can Iterate Map's key and values in lot of ways like getting keySet or by getting entrySet or by using Iterator interface. Lets see all these ways with simple example.
How to Iterate Map key and value


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

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");
  

  System.out.println("Using entrySeT() ---- ");
  
                   for (Map.Entry<String, String> myMap : map.entrySet()) {
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }

  
  System.out.println("\nUsing keySet() ---- ");
  
  for (Object myKey : map.keySet()) {
   System.out.println(myKey.toString() + " : " + map.get(myKey));
  }

  
  System.out.println("\nUsing Iterator interface ---- ");
  
  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


Using entrySeT() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using keySet() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using Iterator interface ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

No comments:
Write comments