Java: How to invert a Hashtable?

Say you have a Hashtable with : number for keys, and a comma deliminated list of letters of values.  Now you want to make another hash table which is the opposite.  The keys for the second Hashtable will be a distinct list of all possible letters from the first Hashtable, and the values will be a comma deliminated list of all the numbers associated with a particular letter.

import java.util.Enumeration;
import java.util.Hashtable;
 
public class HashInversion
{
	public static void main(String[] args)
	{
 
		//hashtable : numbers with lists of letters
		Hashtable num2letter_hash = new Hashtable();
 
		//hashtable letters with list of numbers
		Hashtable letters2num_hash = new Hashtable();
 
		num2letter_hash.put(1,"a,b,c,d");
		num2letter_hash.put(22,"g,e,d");
		num2letter_hash.put(73,"e,g,d");
		num2letter_hash.put(41,"a,v,c,d,b,e");
		num2letter_hash.put(5,"a,l");
		num2letter_hash.put(17,"a");
		num2letter_hash.put(18,"a,l,e");
 
		//loop through all the elements in num2letter_hash
		Enumeration keys = num2letter_hash.keys();
		while( keys.hasMoreElements() )
		{
int key = (int) keys.nextElement();
String content = (String) num2letter_hash.get(key);
//break up the content by commas
String [] letters = content.split(",");
for( int i = 0 ; i < letters.length; i++)
{
//if this letter hasn't been added to the new hash,
//  add it, and set its value to the current key
//if it already exists in the new table, obtain the current value string
//  and append a new number/key to it.
if( letters2num_hash.containsKey(letters[i].toString()) )
{
String previous_num =  (String) letters2num_hash.get(letters[i].toString());
letters2num_hash.put(letters[i].toString(), previous_num+","+key);
}
else
{
letters2num_hash.put( letters[i].toString(), ""+key);
}
}
		}
		//before  (numbers,letter-list)
		System.out.println(num2letter_hash.toString());
		//after   (letters,number-list)
		System.out.println(letters2num_hash.toString());
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *