user3287300
user3287300

Reputation: 151

Sorting HashMap keys into alphabetical order

Current Output:

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

Desired Output:

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

How do I get the first word of each line into alphabetical order?

My code for printing the output is:

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

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

}

Can I apply a Collection.sort on my jumbles/jumblesOrdered ArrayList?


HashMaps

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

    }

Upvotes: 1

Views: 3170

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

If you want a Map with sorted keys, I wouldn't use a HashMap but rather a TreeMap, where the Map keys are sorted for you in their natural order (if the keys implement Comparable) or a chosen order if you use a Comparator.

Upvotes: 2

Related Questions