This is the code I have that reads two files, one with words and the other with the scrambled letters. The program reads and matches the scrambled letters to words in the file. It works but I want to the output to be in alphabetical order. Where in my code can I put in a sort?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws Exception
{
BufferedReader dictionary = new BufferedReader( new FileReader(args[0]) );
BufferedReader jumbles = new BufferedReader( new FileReader(args[1]) );
HashMap<String, List<String>> lookup = new HashMap<String, List<String>>();
while(dictionary.ready())
{
String word = dictionary.readLine();
addWord(word, lookup);
}
dictionary.close();
while(jumbles.ready())
{
String jWord = jumbles.readLine();
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}
jumbles.close();
}
private static String createKey(String word)
{
char[] cword = word.toCharArray();
Arrays.sort(cword);
return new String(cword);
}
private static void addWord(String word, Map<String, List<String>> lookup)
{
String key = createKey(word);
List<String> list = lookup.get(key);
if(list == null)
{
list = new ArrayList<String>();
lookup.put(key, list);
}
list.add(word);
}
}
outputs:
atc act cat tac
otsp post pots stop spot tops opts
gdo dog god
atr rat tar art
arpt trap tarp part
grof frog
sylogs glossy
What I want:
arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops
sylogs glossy
nevermind.
Fixed it with:
while(jumbles.ready())
{
jSorted.add(jumbles.readLine());
}
jumbles.close();
Collections.sort(jSorted);
for(int i = 0; i < jSorted.size(); i++)
{
String jWord = jSorted.get(i);
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}