import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class LoopingMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1000", "Ranjith");
map.put("2000", "Sekar");
map.put("3000", "Bala");
map.put("4000", "Kumar");
map.put("5000", "Rekha");
// Way 1: Using EntrySet
System.out.println("===1. Using Map's EntrySet===");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey() + " >> " + entry.getValue());
}
// Way 2: Using keySet
System.out.println("\n===2. Using Map's KeySet===");
Set<String> str = map.keySet();
for (Object obj : str) {
System.out.println(obj.toString() + " >> " + map.get(obj.toString()));
}
// Way 3: Using Iterator
System.out.println("\n===3. Using Iterator===");
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + " >> " + entry.getValue());
}
// Way 4: Using Map's Value (Iterators only Values in the Map)
System.out.println("\n===4. Using Map's Values===");
Collection<String> collection = map.values();
Iterator<String> itr = collection.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
|