import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class HashMapEx {
public static void main(String args[]) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
// Adding to HashMap
hmap.put(12, "Kabir");
hmap.put(2, "Ravi");
hmap.put(7, "Luis");
hmap.put(49, "Peter");
hmap.put(3, "Aditya");
// Iterate through HashMap
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("Key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
// Get a value based on key
String val = hmap.get(2);
System.out.println("Value for key 2 is: " + val);
// Remove on the basis of key
hmap.remove(3);
System.out.println("Map after removal of key 3 is:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}
Comments
Post a Comment
Post Your Valuable Comments