- Iterating through the Map using iterator
- Iterating through the Map keys
- Iterating through the Map values
- Iterating using a for loop
public class MapIteration
{
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Jan");
map.put(2, "Feb");
map.put(3, "Mar");
map.put(4, "Apr");
map.put(5, "May");
map.put(6, "Jun");
Iterator<Entry<Integer, String>> iter = map.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry<Integer, String> mapEntry = (Map.Entry<Integer, String>) iter.next();
System.out.println("Key: " + mapEntry.getKey() + ", Value :" + mapEntry.getValue());
}
for (Map.Entry<Integer, String> entry : map.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
Iterator keysIter = map.keySet().iterator();
while (keysIter.hasNext())
{
Integer key = (Integer) keysIter.next();
System.out.println("Key: " + key);
}
for (String value : map.values())
{
System.out.println("Value : " + value);
}
}
}
No comments:
Post a Comment