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();
		//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);
letters2num_hash.put( letters[i].toString(), ""+key);
		//before  (numbers,letter-list)
		//after   (letters,number-list)

Leave a Reply

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