Iterating over Map
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Map iteration can be done on the basis of key or value or key value set. Choose iteration according to your requirement.
productMap.put("P001", "Product 1");
productMap.put("P002", "Product 2");
productMap.put("P003", "Product 3");
productMap.put("P004", "Product 4");
productMap.put("P005", "Product 5");
System.out.println("--Iterating over Key Set(Method 1)---");
for(Object key : productMap.keySet()) {
System.out.println(key);
}
System.out.println("--Iterating over Key Set(Method 2)---");
Iterator keyIter = productMap.keySet().iterator();
while (keyIter.hasNext()) {
String element = (String)keyIter.next();
System.out.println(element);
}
System.out.println("--Iterating over Value Set--");
Iterator valueIter = productMap.values().iterator();
while(valueIter.hasNext()) {
System.out.println(valueIter.next());
}
System.out.println("--Iterating over Key Value Set--");
Iterator keyValIter = productMap.entrySet().iterator();
while(keyValIter.hasNext()) {
Map.Entry entry = (Map.Entry)keyValIter.next();
System.out.println(entry.getKey() + " => " + entry.getValue());
}
Chose iterator carefully for improved performance.
April 3, 2008 | Filed Under Java
Related Post
- No related posts
Comments
Leave a Reply