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

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

    You can do that using simple List. Try following code.

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    
    /**
     *
     * @author Masudul Haque
     */
    public class LengthSort {
        public static void main(String[] args) {
            List list=new ArrayList<>();
            list.add("cowa");
            list.add("cow");
            list.add("aow");
            Collections.sort(list, new Comparator() {
    
                @Override
                public int compare(String o1, String o2) {
                    if(o1.length()>o2.length()){
                        return 1;
                    }else{
                        return o1.compareTo(o2);
                    }
                }
            });
    
            System.out.println(list);
        }
    }
    

提交回复
热议问题