How to exatact HashTable using KeySet(), Values(), Keys() and Elements() method using Iterator?
Here is complete code example of How to use Iterator in Java. This Java program creates Hashtable, populate HashTable and than uses Iterator to traverse Map and prints key and value for each Entry. This Java Program uses Generic version of Iterator to ensure type-safety and avoid casting .
package com.mindclues; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class IteratorTest { public static void main(String[] args) { HashtablehTable = new Hashtable (); hTable.put(new Integer(1), "A"); hTable.put(new Integer(2), "B"); hTable.put(new Integer(4), "C"); hTable.put(new Integer(3), "D"); //Getting Set of keys for Iterator Set > stockSet = hTable.entrySet(); // Using Iterator to loop Map in Java, here Map implementation is Hashtable Iterator > i = stockSet.iterator(); System.out.println("Iterating Hashtable in Java"); //Iterator start while (i.hasNext()) { Map.Entry m = i.next(); int key = m.getKey(); String value = m.getValue(); System.out.println("Key :" + key + " Value :" + value); } } }
Iterating Hashtable in Java Key :4 Value :C Key :3 Value :D Key :2 Value :B Key :1 Value :A
post a comment