sort words by length and then by alphabetical order

后端 未结 4 1628
既然无缘
既然无缘 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 06:50

    Try looking at the Collections framework List might be a good place to start, and look at Comparable/Comparators. That might help.

    0 讨论(0)
  • 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<String> {
      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.

    0 讨论(0)
  • 2021-01-29 07:01

    You should define a Comparator, so that it compares the two strings in a right manner. In your case, the shorter string will go prior to a longer string; if sizes are equal - the order is alphabetic. Then you use this Comparator to do the sorting - use Collections.sort() for it.

    0 讨论(0)
  • 2021-01-29 07:08

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

    public static final Comparator<String> wordComparator = new Comparator<String>()
    {
        @Override
        public int compare(String o1, String o2) 
        {
            if(o1.length() == o2.length()) return o1.compareToIgnoreCase(o2);
            else return o1.length() - o2.length();
        }
    };
    
    ArrayList<String> tmp = new ArrayList<>();
    //Add words
    Collections.sort(tmp, wordComparator);
    
    0 讨论(0)
提交回复
热议问题