Java Collection How to - Get key and value set respectively from HashMap








Question

We would like to know how to get key and value set respectively from HashMap.

Answer

/*  w  ww  .  j  av  a 2s  . c  om*/
import java.util.HashMap;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {

    HashMap<String, String> hashmap = new HashMap<String, String>();

    hashmap.put("one", "1");
    hashmap.put("two", "2");
    hashmap.put("three", "3");
    hashmap.put("four", "4");
    hashmap.put("five", "5");
    hashmap.put("six", "6");

    Iterator<String> keyIterator = hashmap.keySet().iterator();
    Iterator<String> valueIterator = hashmap.values().iterator();

    while (keyIterator.hasNext()) {
      System.out.println("key: " + keyIterator.next());
    }

    while (valueIterator.hasNext()) {
      System.out.println("value: " + valueIterator.next());
    }
  }
}

The code above generates the following result.