CodesJava

Easy learning with example program codes

how to iterate through hashtable in java?


Hashtable:

Hashtable extends Dictionary class and implements Map interface. It contains elements in key-value pair. It not allowed duplicate key. It is synchronized. It can’t contain null key or value. It uses hashcode() method for finding the position of the elements.

To iterate through hashtable in java, first we have to get all keys as set object and then fetch each element using key.

Example:

package com.codesjava;
 
import java.util.Hashtable;
import java.util.Set;
 
public class Test {
  public static void main(String args[]){
	//Create Hashtable object.
	Hashtable<String, String> hashtable = new Hashtable<String, String>();
	//Add objects to the Hashtable.
	hashtable.put("1", "Jai");
	hashtable.put("2", "Mahesh");
	hashtable.put("3","Vivek");
        System.out.println(hashtable);
        Set<String> keys = hashtable.keySet();
        for(String key: keys){
            System.out.println("Value of "+key+" is: "+hashtable.get(key));
        }
  }
}

Output

{3=Vivek, 2=Mahesh, 1=Jai}
Value of 3 is: Vivek
Value of 2 is: Mahesh
Value of 1 is: Jai
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki