按字符数对字符串进行排序

时间:2013-11-21 09:42:40

标签: java string sorting numbers character

我有问题。 我想用字符串中的字符数从txt文件中对字符串进行排序 例如 输入: AAA 一个 AA 输出: 一个 AA AAA 我创建了包含字母和字母串的字符串。创建的集合包含多少个字符串字符,但我无法理解

我如何按字符串

中的字符数排序
public class SortingFile {
public static void main(String[] args) throws IOException {

try{
    File inputFile=new File("c:/a.txt");
    Reader r=new FileReader(inputFile);
    BufferedReader br=new BufferedReader(r);

    List <String> list = new LinkedList<String>();
    List <Integer> listLength= new LinkedList<Integer>();

    String line=br.readLine();
    list.add(line);

    while (line!=null){
        line=br.readLine(); 
        list.add(line);
        }

    int arrsize=(list.size())-1;
    System.out.println("line array size= "+arrsize);
    list.remove(arrsize); //delete last element (he is null )

    System.out.println("Before sorting by alphabet: "+list);
    Collections.sort(list);//sorting by alphabet
    System.out.println("After sorting by alphabet: " +list);

    for (int i=0;i!=list.size();i++){ //add string lenght to collection
        String a=list.get(i);
        int aa=a.length();
        listLength.add(aa);
    }
    System.out.println("lineLength:"+listLength);
    Collections.sort(listLength); // sotring by asc
    System.out.println("lineLength2:"+listLength);
    br.close();

}catch (FileNotFoundException e1){
System.out.println("File ''a.txt'' Not Found :(");
e1.printStackTrace();
}


 } 
}

4 个答案:

答案 0 :(得分:2)

尝试使用以下Comparator

 Collections.sort(list, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.length()-o2.length();
        }
    });

答案 1 :(得分:0)

使用额外Collections.sort(java.util.List, java.util.Comparator)参数的Comparator

这可以让你改变事物的排序方式。

答案 2 :(得分:0)

Collections.sort有一个重载方法,您可以在其中提供comparator。对比较器进行编码,您将比较字符串的长度并返回更大或更小的内容(取决于您是要升序还是降序)。然后只需调用你的Collections.sort(myListOfString,myComporator);,结果将是按长度排序的字符串列表。

答案 3 :(得分:0)

将比较器传递给Collection.sort(list,yourSorter)方法,并使用您想要在其中使用的任何逻辑。

Collections.sort(list, sortAccordingToLength);

 static Comparator<String> sortAccordingToLength= new Comparator<String> {
  public int compare(String a, String b) {
      return a.length()-b.length();
  }
});