排序CSVRecords列表(apache commons)

时间:2016-12-26 20:29:16

标签: java sorting collections

我收到了这个CSV文件:

User ID,First Name
3,David 
4,Ruby 
10,Ruby 

我想按照以下方法按升序排序:

@Override
    public void sort(InputStream in, OutputStream out, String field_name, Comparator<CSVRecord> comparator) throws IOException {

     Reader inputStreamReader = new InputStreamReader(in);  
     Iterable<CSVRecord> csvRecords = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(inputStreamReader);

     List<CSVRecord> csvRecordsList = Lists.newArrayList(csvRecords);
     Collections.sort(csvRecordsList,comparator);

     Writer outputStreamWriter = new OutputStreamWriter(out);
     CSVPrinter cvsPrinter = CSVFormat.RFC4180.print(outputStreamWriter); 
     cvsPrinter.printRecords(csvRecordsList);
     cvsPrinter.flush();
     cvsPrinter.close();

问题是Collections.sort没有做任何事情。这与我提供的参数相似:

 Comparator<CSVRecord> comparator = (op1,op2) -> op2.get(field).compareTo(op1.get(field));

我做错了什么?

1 个答案:

答案 0 :(得分:1)

CSVRecord.get()会返回String,因此您实际上在比较器中调用了String.compareTo而不是Integer.compareTo。试试这个:

Comparator<CSVRecord> comparator = (op1,op2) -> Integer.valueOf(op2.get(field)).compareTo(Integer.valueOf(op1.get(field)));