Mega Code Archive

 
Categories / Java / Collections Data Structure
 

Listing the Elements of a Collection

import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Main {   public static void main(String[] argv) {     List collection = new ArrayList();     // For a set or list     for (Iterator it = collection.iterator(); it.hasNext();) {       Object element = it.next();     }     Map map = new HashMap();     // For keys of a map     for (Iterator it = map.keySet().iterator(); it.hasNext();) {       Object key = it.next();     }     // For values of a map     for (Iterator it = map.values().iterator(); it.hasNext();) {       Object value = it.next();     }     // For both the keys and values of a map     for (Iterator it = map.entrySet().iterator(); it.hasNext();) {       Map.Entry entry = (Map.Entry) it.next();       Object key = entry.getKey();       Object value = entry.getValue();     }   } }