2014-08-28 52 views
-6

csv文件2级排序我的文件是这样的:如何实现在使用Java

55 44 1 
55 33 0 
55 77 2 
55 88 3 
44 333 1 
44 444 0 
11 6 1 
11 3 3 
11 5 2 

我需要重新排序,如:

11 6 1 
11 5 2 
11 3 3 
44 444 0 
44 333 1 
55 33 0 
55 44 1 
55 77 2 
55 88 3 

谁能帮助我实现这一目标?

+4

请提供一些努力,最好是代码。 – 2014-08-28 10:47:25

+1

我想如果你在谷歌2搜索可以在15-30分钟内找到你的解决方案。 “使用Java从文件读取”和“使用Java重新排列数组/列表” – AlvaroAV 2014-08-28 10:48:43

回答

1

当它只是一个小文件,你可以解决它像这样

  • 读取所有行到一个列表
  • 使用自己的比较实现自己的Comparator
  • 排序列表

这个例子只是一个PoC。任何不需要显示该原则的内容都被省略了。

import java.io.IOException; 
import java.nio.charset.Charset; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 

/** 
* @author SubOptimal 
*/ 
public class Main { 

    public static Comparator<String> getComparator() { 
     return new Comparator<String>() { 
      @Override 
      public int compare(String o1, String o2) { 
       // split the lines to compare by whitespaces 
       String[] columns1 = o1.split("\\s+"); 
       String[] columns2 = o2.split("\\s+"); 
       // compare first column 
       if (columns1[0].compareTo(columns2[0]) != 0) { 
        return columns1[0].compareTo(columns2[0]); 
       } 
       // compare third column 
       if (columns1[2].compareTo(columns2[2]) != 0) { 
        return columns1[2].compareTo(columns2[2]); 
       } 
       // both lines have equal 
       return 0; 
      } 
     }; 
    } 

    public static void main(String[] args) throws IOException { 
     final Path path = Paths.get("input.csv"); 
     // read all lines into a list of String 
     List<String> lines = Files.readAllLines(path, DEFAULT_CHARSET); 
     // sort the list using your own comparator 
     Collections.sort(lines, getComparator()); 
     // output the sorted list 
     for (String line : lines) { 
      System.out.println(line); 
     } 
    } 

    private static final Charset DEFAULT_CHARSET = Charset.defaultCharset(); 
} 
+1

非常感谢... – 2014-08-28 13:41:55