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
Try looking at the Collections framework List might be a good place to start, and look at Comparable/Comparators. That might help.
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.
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.
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);