Get key set and value set from map and use Iterator to loop through them : HashMap « Collections Data Structure « Java






Get key set and value set from map and use Iterator to loop through them

      
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();

    map.put(new Integer(1), "One");
    map.put(new Integer(2), "Two");
    map.put(new Integer(3), "Three");
    map.put(new Integer(4), "Four");
    map.put(new Integer(5), "Five");

    System.out.println("Map Values Before: ");
    Set keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
      Integer key = (Integer) i.next();
      String value = (String) map.get(key);
      System.out.println(key + " = " + value);
    }

    System.out.println("\nRemove element with key 6");
    map.remove(new Integer(6));

    System.out.println("\nMap Values After: ");
    keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
      Integer key = (Integer) i.next();
      String value = (String) map.get(key);
      System.out.println(key + " = " + value);
    }
  }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Iterate through the values of Java HashMap example
2.Get Synchronized Map from Java HashMap example
3.Check if a particular key exists in Java HashMap example
4.Check if a particular value exists in Java HashMap example
5.Get Set view of Keys from Java HashMap example
6.Get Size of Java HashMap
7.Remove all values from Java HashMap example
8.Remove value from Java HashMap
9.Create Java Hashtable from HashMap
10.Sort an HashMap based on the keys
11.For keys of a map
12.For values of a map
13.For both the keys and values of a map
14.Storing Primitive Types in a Collection
15.Creating a Copy of a Collection: the objects are not cloned.
16.Use Iterator to loop through the map key set
17.Generic hashmap with String as key and Integer as valueGeneric hashmap with String as key and Integer as value
18.Clones a map
19.Hash map for counting references to Object keys.
20.Extended Version of java.util.HashMap that provides an extended get method accpeting a default value.
21.Compact HashMap
22.This class wraps a HashMap and provides methods by which key objects can be associated with "counting" values.
23.This extension of HashMap support duplicate keys
24.Concurrent Hopscotch HashMap