sort words by length and then by alphabetical order

后端 未结 4 1629
既然无缘
既然无缘 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 06:56

    You should simply add all matching words to ArrayList and then use Collections.sort with custom comparator e.g.

    class Comparator implements Comparator {
      public int compare(String o1, String o2) {
        if (o1.length() > o2.length()) {
          return 1;
        } else if (o1.length() < o2.length()) {
          return -1;
        } else {
          return o1.compareTo(o2);
        }
      }
    }
    

    And then output sorted list to test.txt.

    Or you may put matching words in TreeSet with custom comparator to be sure you don't have duplicates.

提交回复
热议问题