HashMap输出问题

时间:2015-04-18 19:07:22

标签: java hashmap

我正在尝试使用HashMap来做一个项目,在这个项目中我读了一个混乱的单词列表和一个实际字典单词的文件,并使用HashMap查找在混乱的单词文件中匹配的所有单词并打印出来。问题是我无法打印出正确的词典形式,只是一个规范版本(字母按字母顺序排列)。

public class Jumbles {
    public static void main(String[] args) throws Exception
    {
        if (args.length < 2 ) die

        BufferedReader dictionaryFile = new BufferedReader( new FileReader( args[0] ));
        BufferedReader jumbleFile = new BufferedReader( new FileReader( args[1] ));

        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        ArrayList<String> jumbleWords = new ArrayList<String>();
        ArrayList<String> dictionaryWords = new ArrayList<String>(); 

        while(jumbleFile.ready())
        {
            String word = jumbleFile.readLine();
            String canWord = toCanonical(word); 
            jumbleWords.add(word); 
            map.put(canWord, new ArrayList<String>()); 
        }
        Collections.sort(jumbleWords); 

        while(dictionaryFile.ready())
        {
            String dictWord = dictionaryFile.readLine(); 
            dictionaryWords.add(dictWord); 
        }
        for(String dictionaryWord : dictionaryWords)
        {
            String canDictWord = toCanonical(dictionaryWord); 
            if(map.containsValue(canDictWord))
            {
                ArrayList<String> listOfWords = map.get(canDictWord); 
                listOfWords.add(dictionaryWord);
            }
        }
        ArrayList<String> keysList = new ArrayList(map.keySet());
        Collections.sort(keysList);
        for(String key : keysList)
        {
            System.out.print(key); 

            ArrayList<String> list = map.get(key);
            Collections.sort(list);
            for(String word : list)
            {
                System.out.print(" " + word);   
            }
            System.out.println(); 
        }
    } 

    private static void die( String errmsg )
    {
        System.out.println( "\nFATAL ERROR: " + errmsg + "\n" );
        System.exit(0);
    }

    private static String toCanonical( String word )
    {
        char[] letters = word.toCharArray();
        Arrays.sort(letters);
        return new String(letters);
    }
} 

0 个答案:

没有答案