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

Iterate Map Entries 

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<Entry<K, V>> entrySet();
 - Returns all Entries in the Map as a Set.


File Name  :  
com/bethecoder/tutorials/utils/maps/IterateEntries.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.maps;

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

public class IterateEntries {

  /**
   @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<Entry<Integer, String>> entries = numMap.entrySet().iterator();
    Entry<Integer, String> entry = null;
    
    while (entries.hasNext()) {
      entry = entries.next();
      System.out.println(entry.getKey() "=" + entry.getValue());
    }
  }

}
   

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

1=ONE
2=TWO
3=THREE



 
  


  
bl  br