package com.usr.collections;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class LoopingMap {
public static void main(String[] args) {
Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "sunday");
hm.put(2, "monday");
hm.put(3, "tueday");
hm.put(4, "wednesday");
hm.put(5, "thursday");
hm.put(6, "friday");
hm.put(7, "saturday");
System.out.println("1.Using for each loop");
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("2.Retriving keys and values ");
Set<Integer> set = hm.keySet();
Iterator<Integer> itr = set.iterator();
while (itr.hasNext()) {
Integer key = (Integer) itr.next();
System.out.println(key + ":" + hm.get(key));
}
System.out.println("3.Retrieving values");
Collection<String> col = hm.values();
Iterator<String> itr1 = col.iterator();
while (itr1.hasNext()) {
String value = (String) itr1.next();
System.out.println(value + ":");
}
System.out.println("4.Retrieving keys and values using Iterator");
Iterator<Map.Entry<Integer, String>> entries = hm.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, String> entry = entries.next();
System.out.println(entry.getValue() + ":" + entry.getKey());
}
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.