Reputation: 97
I am working on a project where I will be given two files; one with jumbled up words and the other with real words. I then need to print out the list of jumbled up words in alphabetical order with its matching real word(s) next to it. The catch is that there can be multiple real words per jumbled up word.
For example:
cta cat
ezrba zebra
psot post stop
I completed the program without accounting for the multiple words per jumbled up words, so in my HashMap I had to change < String , String > to < String , List < String > >, but after doing this I ran into some errors in the .get and .put methods. How can I get multiple words stored per key for each jumbled up word? Thank you for your help.
My code is below:
import java.io.*;
import java.util.*;
public class Project5
{
public static void main (String[] args) throws Exception
{
BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) );
BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) );
HashMap<String, List<String>> dWordMap = new HashMap<String, List<String>>();
ArrayList<String> scrambled = new ArrayList<String>();
while (dictionaryList.ready())
{
String word = dictionaryList.readLine();
//throw in an if statement to account for multiple words
dWordMap.put(createKey(word), word);
}
dictionaryList.close();
ArrayList<String> scrambledList = new ArrayList<String>();
while (scrambleList.ready())
{
String scrambledWord = scrambleList.readLine();
scrambledList.add(scrambledWord);
}
scrambleList.close();
Collections.sort(scrambledList);
for (String words : scrambledList)
{
String dictionaryWord = dWordMap.get(createKey(words));
System.out.println(words + " " + dictionaryWord);
}
}
private static String createKey(String word)
{
char[] characterWord = word.toCharArray();
Arrays.sort(characterWord);
return new String(characterWord);
}
}
Upvotes: 0
Views: 567
Reputation: 564
you could do something like :
replace the line:
dWordMap.put(createKey(word), word);
with:
String key = createKey(word);
List<String> scrambled = dWordMap.get(key);
//make sure that scrambled words list is initialized in the map for the sorted key.
if(scrambled == null){
scrambled = new ArrayList<String>();
dWordMap.put(key, scrambled);
}
//add the word to the list
scrambled.add(word);
Upvotes: 2
Reputation: 343
dWordMap.put(createKey(word), word);
The dwordMap is of type HashMap>. So instead of word i.e. String it should be List.
Upvotes: 0