将HashMap键排序为字母顺序

时间:2014-04-10 03:21:40

标签: java

当前输出:

atc act cat tac
otsp post pots stop spot tops opts
gdo dog god
atr rat tar art
arpt trap tarp part
grof frog

期望的输出:

arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops

如何将每行的第一个单词按字母顺序排列?

我打印输出的代码是:

for (int i = 0; i < jumblesOrdered.size(); i++) {
String wordAnswer = jumblesOrdered.get(i);

System.out.println(jumbles.get(i) + " " + dictWordHM.get(wordAnswer));

}

我可以在我的jumbles / jumblesOrdered ArrayList上应用Collection.sort吗?


包含HashMap

    for (int i = 0; i < dictionaryOrdered.size(); i++) {
        String word = dictionary.get(i);
        String sortedWord = dictionaryOrdered.get(i);

        if (dictWordHM.get(sortedWord) == null) {
            dictWordHM.put(sortedWord, word);
        } else {
            dictWordHM.put(sortedWord, dictWordHM.get(sortedWord) + " "
                    + word);
        }
    }

    for (int i = 0; i < jumblesOrdered.size(); i++) {
        String word = jumbles.get(i);
        String sortedWord = jumblesOrdered.get(i);

        if (jumbleWordHM.get(sortedWord) == null) {
            jumbleWordHM.put(sortedWord, word);
        } else {
            jumbleWordHM.put(sortedWord, jumbleWordHM.get(sortedWord) + " "
                    + word);
        }

    }

1 个答案:

答案 0 :(得分:2)

如果你想要一个带有排序键的Map,我不会使用HashMap而是使用TreeMap,其中Map键按照自然顺序为你排序(如果键实现Comparable)或者选择顺序你使用比较器。