How to Copy Key-value Pairs from HashMap to HashTable in Java


Here we will learn how to copy all key value pairs from HashMap Object to Hashtable Object with putAll method of java Hashtable class.

Source Code

package com.beginner.examples;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashMapToHashTable {

	public static void main(String[] args) {
		// Create a HashMap
		HashMap map = new HashMap();

		// Store some key-value pairs
		map.put("a", 97);
		map.put("b", 98);
		map.put("c", 99);
		map.put("d", 100);

		// Create a HashTable
		Hashtable table = new Hashtable();
		
		// Store some key-value pairs
		table.put("e", 101);
		table.put("f", 102);
		
		System.out.println("Hashtable:");
		printKey_Value(table);
		System.out.println("*************");
		
		//Add a HashMap
		table.putAll(map);
		
		System.out.println("After adding:");
		printKey_Value(table);
	}
	/*
	 * This method is used to print the key-value pairs in the HashTable.
	 */
	public static void printKey_Value(Hashtable table)
	{
		//Gets a collection of keys in the HashTable
		Set keyTable = table.keySet();
		
		//Iterate through the set
		Iterator iterator = keyTable.iterator();
		
		while(iterator.hasNext())
		{
			String key = iterator.next();
			Integer value = table.get(key);
			System.out.println(key+":::"+value);
		}
		
	}

}

Output:

Hashtable:
f:::102
e:::101
*************
After adding:
b:::98
a:::97
f:::102
e:::101
d:::100
c:::99

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments