Created
January 7, 2013 14:57
-
-
Save madan712/4475552 to your computer and use it in GitHub Desktop.
Java - Various ways to iterate a Map (Hashtable, HashMap, TreeMap, LinkedHashMap)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collection; | |
import java.util.Enumeration; | |
import java.util.Hashtable; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.Set; | |
public class IterateMap { | |
public static void main(String[] args) { | |
Map<String, String> colorCode = new Hashtable<String, String>(); | |
colorCode.put("Red", "FF0000"); | |
colorCode.put("Blue", "0000FF"); | |
colorCode.put("Green", "008000"); | |
colorCode.put("Black", "000000"); | |
colorCode.put("White", "FFFFFF"); | |
System.out.println("method 1 - Using Iterator"); | |
Set<String> lSet = colorCode.keySet(); | |
Iterator<String> itr1 = lSet.iterator(); | |
while (itr1.hasNext()) { | |
String key = itr1.next(); | |
System.out.println(key + " " + colorCode.get(key)); | |
} | |
System.out.println("method 2 - Using Enumeration for Hashtable"); | |
Enumeration<String> enu1 = ((Hashtable) colorCode).keys(); | |
while (enu1.hasMoreElements()) { | |
String key = enu1.nextElement(); | |
System.out.println(key + " " + colorCode.get(key)); | |
} | |
System.out.println("method 3 - Using Collection"); | |
Collection<String> col = colorCode.values(); | |
Iterator<String> itr2 = col.iterator();// obtain an Iterator for Collection | |
while (itr2.hasNext()) { | |
System.out.println(itr2.next()); | |
} | |
System.out.println("method 4 - Using Enumeration only values"); | |
Enumeration<String> enu2 = ((Hashtable) colorCode).elements(); | |
while (enu2.hasMoreElements()) { | |
System.out.println(enu2.nextElement()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment