HashMap Keys Iterator Example

In this example, we will write a Java code to iterate over the keys of a HashMap using the Iterator interface.

HashMap Keys Iterator Example

Here is the Java example to iterate over keys of a HashMap:
package com.java.tutorials.collections;

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

/**
 * Iterator Examples
 * @author Ramesh Fadatare
 *
 */
public class IteratorExample {
 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("key1", "value1");
  map.put("key2", "value2");
  map.put("key3", "value3");
  map.put("key4", "value4");

  Iterator<String> iterator = map.keySet().iterator();
  while (iterator.hasNext()) {
   String key = (String) iterator.next();
   System.out.println(key);
  }
 }
}
Output:
key1
key2
key3
key4

References


Comments