Java Hashmap Iterator


 

Java Hashmap Iterator

In this section of tutorial we will learn how to use the HashMap with the Iterator interface. We will create an example to display the contents of the hashMap using Iterator

In this section of tutorial we will learn how to use the HashMap with the Iterator interface. We will create an example to display the contents of the hashMap using Iterator

  • Java HashMap Iterator is a collection class. It implements the Map interface.
  • It keeps the data in the key and value form.
  • Java HashMap has no iterator method.
  • So use the entrySet() method.It returns the data in Set object form.
  • Set's all elements can be traversed by the Iterator.


Java Hashmap Iterator Example
import java.util.*;
public class hashmap1 {
	public static void main(String[] args) {
		HashMap map = new HashMap();
		map.put("a", "Apple");
		map.put("b", "Boy");
		map.put("c", "cat");
		map.put("d", "Dog");
		Set s = map.entrySet();
		Iterator it = s.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output

d=Dog b=Boy c=cat a=Apple

Ads