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

后端 未结 5 948
[愿得一人]
[愿得一人] 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 19:06

    The easiest way would be to write a Comparator. The Comparator would receive two words, and compare them. If the first was shorter than the second, it should return -1. If the second was shorter than the first, it would return 1. If they are the same length, it should call the default String compareTo method. You can then simply sort your list using this custom Comparator.

提交回复
热议问题