2014-10-28 342 views
-1

下面你可以看到我的代码。它从字典中读取单词并将与特定模板匹配的单词复制到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(); 
     } 
    } 
} 
+0

你尝试过什么?必须有成千上万的问题解释如何在Java中排序。 – 2014-10-28 19:03:57

回答

1

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

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

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

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

0

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

1

您应该定义一个比较器,以便以正确的方式比较两个字符串。在你的情况下,较短的字符串会先于较长的字符串;如果尺寸相同 - 顺序是字母顺序。 然后您使用此比较器进行排序 - 使用Collections.sort()

0

所有的单词添加到列表然后进行排序使用比较:

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