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

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

    you want to use a string comparator that compares by length 1st. like so:

    public class LengthFirstComparator implements Comparator {
        @Override
        public int compare(String o1, String o2) {             
            if (o1.length()!=o2.length()) {
                return o1.length()-o2.length(); //overflow impossible since lengths are non-negative
            }
            return o1.compareTo(o2);
        }
    }
    

    then you could simply sort your Strings by calling Collections.sort(yourStringList, new LengthFirstComparator());

提交回复
热议问题