tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Java > Collection > Maps > Iterate Map

Iterate Map 

The following example shows creating a Map and iterating its entries. HashMap and Hashtable are two implementations of Map interface. Hashtable is synchronized where as HashMap is not. Map provides the following APIs,

public int size();
 - Returns the number of entries in the Map.
 
public boolean isEmpty();
 - Returns true if the Map contains more than one entry otherwise returns false. 
 
public Set keySet();
 - Returns all keys in the Map as a Set.


File Name  :  
com/bethecoder/tutorials/utils/maps/Iterate.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.utils.maps;

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

public class Iterate {

  /**
   @param args
   */
  public static void main(String[] args) {

    Map<Integer, String> numMap = new HashMap<Integer, String>();
    numMap.put(new Integer(1)"ONE");
    numMap.put(new Integer(2)"TWO");
    numMap.put(new Integer(3)"THREE");
    
    System.out.println("Map Size : " + numMap.size() " " + numMap);
    System.out.println("Is Map Empty ? : " + numMap.isEmpty());
    System.out.println();
    
    Iterator<Integer> keys = numMap.keySet().iterator();
    Integer key = null;
    String value = null;
    
    while (keys.hasNext()) {
      key = keys.next();
      value = numMap.get(key);
      
      System.out.println(key + "=" + value);
    }
  }

}
   

It gives the following output,
Map Size : 3 {1=ONE, 2=TWO, 3=THREE}
Is Map Empty ? : false

1=ONE
2=TWO
3=THREE


                    Print

   



Books Recommendation

 
 
bl  br