Open In App

How to Convert a HashTable to Other Collections Types in Java?

In Java, a Hashtable is a data structure that stores the data in the form of key and value pairs. And each key is mapped to a specific value. It implements the Map interface. HashTable provides a simple way to access the data using the unique keys.

In this article, we will learn how to convert a HashTable to other Collection types in Java.



Note: HashTable does not allow NULL keys or NULL values.

Conversion of HashTable to other Collections:

There are several types of converting the HashTable to other collections, here are some conversions:



Program to Convert a HashTable to Other Collections Types in Java

Below is the implementation of Convert a HashTable to Other Collections Types:




// Java program to convert a HashTable to other Collections types 
import java.util.*;
public class ExampleConversion 
{
    public static void main(String[] args) 
    {
        // create a HashTable
        Hashtable<Integer, String> hashTable = new Hashtable<>();
        hashTable.put(1, "One");
        hashTable.put(2, "Two");
        hashTable.put(3, "Three");
  
        // converting  HashTable to ArrayList
        List<Integer> arrayList = new ArrayList<>(hashTable.keySet());
        System.out.println("Converted ArrayList Output: " + arrayList);
  
        // converting HashTable to HashSet
        Set<String> hashSet = new HashSet<>(hashTable.values());
        System.out.println("Converted HashSet output : " + hashSet);
  
        // converting  HashTable to TreeMap
        Map<Integer, String> treeMap = new TreeMap<>(hashTable);
        System.out.println("Converted TreeMap output : " + treeMap);
  
        // converting HashTable to LinkedHashMap
        Map<Integer, String> linkedHashMap = new LinkedHashMap<>(hashTable);
        System.out.println("Converted LinkedHashMap output : " + linkedHashMap);
    }
}

Output
Converted ArrayList Output: [3, 2, 1]
Converted HashSet output : [One, Two, Three]
Converted TreeMap output : {1=One, 2=Two, 3=Three}
Converted LinkedHashMap output : {3=Three, 2=Two, 1=One}

Explanation of the above Program:

In the above example,


Article Tags :