sort words by length and then by alphabetical order

后端 未结 4 1660
既然无缘
既然无缘 2021-01-29 06:22

Below you can see my code. It reads words from dictionary and copy words that match specific patern to test.txt. My qusetion is how to sort words in test.txt first by LENGTH and

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-29 07:08

    Add all your words to a list then sort using a comparator:

    public static final Comparator wordComparator = new Comparator()
    {
        @Override
        public int compare(String o1, String o2) 
        {
            if(o1.length() == o2.length()) return o1.compareToIgnoreCase(o2);
            else return o1.length() - o2.length();
        }
    };
    
    ArrayList tmp = new ArrayList<>();
    //Add words
    Collections.sort(tmp, wordComparator);
    

提交回复
热议问题