按字母顺序排序HashMap程序的输出

时间:2016-10-11 04:13:28

标签: java sorting hashmap

这是我的代码,它读取两个文件,一个带有单词,另一个带有乱码。程序读取并将加扰的字母与文件中的单词匹配。它工作但我希望输出按字母顺序排列。在我的代码中我可以进行排序吗?

#i_frame {
    display: none;
}

输出:

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); } }

我想要的是什么:

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

没关系。

修正了:

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

1 个答案:

答案 0 :(得分:0)

您可以创建字符串列表然后对它们进行排序

    List<String> result = new ArrayList<>();
    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){
            result.add(jWord + " " + wordsString);
        }
    }
    jumbles.close();
    result.sort(String::compareTo);
    result.forEach(System.out::println);