Java: Sort a list of words by length, then by alphabetical order

后端 未结 5 952
[愿得一人]
[愿得一人] 2021-01-13 18:20

I am told to have a list of words sorted by length, and those that have the same length are sorted by alphabetical order. This is what I have for the method that does that s

5条回答
  •  不思量自难忘°
    2021-01-13 18:50

    By far the easiest and best way is to write a custom comparator as other answers say.

    But to do it a similar way you were attempting would be to make the length the key and rather then having a single string as the value have a list of all the words of that length. So a map of the form

    Map>
    

    You could then call the key of any length and return a sorted list of words like this

    Collections.sort(yourMap.get(theLength))
    

    BUT far more complicated then just using a comparator

提交回复
热议问题