按长度排序,然后按字母顺序排序

下面你可以看到我的代码。 它从字典中读取单词并将与特定patern匹配的单词复制到test.txt。 我的问题是如何首先按照LENGTH对test.txt中的单词进行排序,以及何时按长度排序,然后按字母顺序排序。 例如。

我有:

  • 汽车
  • 老鼠
  • ABC
  • 遗传资源

我需要的

  • ABC
  • 汽车
  • 遗传资源
  • 老鼠

我的列表包含超过10000个单词。

package test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Pattern; public class moja { public static void main(String[] args) { try { File file = new File("SloveneLexicon.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(file), "UTF8")); String vrstica; File test = new File("test.txt"); FileWriter fw = new FileWriter(test); while ((vrstica = bufferedReader.readLine()) != null) { String s = vrstica; String[] dobi_besedo_v_vrstici = s.split("\\s+"); String prva_beseda = dobi_besedo_v_vrstici[0]; String tretja_beseda = dobi_besedo_v_vrstici[2]; String nova_vrstica = System.getProperty("line.separator"); Pattern ena = Pattern.compile("S\\p{L}\\p{L}ei\\p{L}*"); if(ena.matcher(tretja_beseda).matches()){ fw.write(prva_beseda+nova_vrstica); fw.write("\n");} Pattern dva = Pattern.compile("P\\p{L}\\p{L}\\p{L}ei\\p{L}*"); if(dva.matcher(tretja_beseda).matches()){ fw.write(prva_beseda+nova_vrstica); } } fw.close(); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } 

您应该简单地将所有匹配的单词添加到ArrayList,然后使用Collections.sort和自定义比较器,例如

 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); } } } 

然后将排序列表输出到test.txt。

或者您可以将TreeSet中的匹配单词与自定义比较器放在一起,以确保您没有重复项。

您应该定义一个Comparator,以便以正确的方式比较两个字符串。 在您的情况下,较短的字符串将在较长的字符串之前; 如果大小相等 – 顺序是字母。 然后使用此Comparator进行排序 – 使用Collections.sort()

尝试查看集合框架列表可能是一个很好的起点,并查看可比较/比较器。 这可能有所帮助。

将所有单词添加到列表中,然后使用比较器排序:

 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);