java csv排序,如何使用Java中的特定字段对CSV文件中的数据排序?

I want to read a CSV file in Java and sort it using a particular column. My CSV file looks like this:

ABC,DEF,11,GHI....

JKL,MNO,10,PQR....

STU,VWX,12,XYZ....

Considering I want to sort it using the third column, my output should look like:

JKL,MNO,10,PQR....

ABC,DEF,11,GHI....

STU,VWX,12,XYZ....

After some research on what data structure to use to hold the data of CSV, people here suggested to use Map data structure with Integer and List as key and value pairs in this question:

Map>

where the value, List = {[ABC,DEF,11,GHI....], [JKL,MNO,10,PQR....],[STU,VWX,12,XYZ....]...}

And the key will be an auto-incremented integer starting from 0.

So could anyone please suggest a way to sort this Map using an element in the 'List' in Java? Also if you think this choice of data structure is bad, please feel free to suggest an easier data structure to do this.

Thank you.

解决方案

I would use an ArrayList of ArrayList of String:

ArrayList>

Each entry is one line, which is a list of strings.

You initialize the list by:

List> csvLines = new ArrayList>();

To get the nth line:

List line = csvLines.get(n);

To sort you write a custom Comparator. In the Constructor of that comparator you can pass the field position used to sort.

The compare method then gets the String value on stored position and converts it to a primitive ava type depending on the position. E.g you know that at position 2 in the csv there is an Integer, then convert the String to an int. This is neccessary for corretcly sorting. You may also pass an ArrayList of Class to the constructor such that it knows which field is what type.

Then use String.compareTo() or Integer.compare(), depending on column position etc.

Edit example of working code:

List> csvLines = new ArrayList>();

Comparator> comp = new Comparator>() {

public int compare(ArrayList csvLine1, ArrayList csvLine2) {

// TODO here convert to Integer depending on field.

// example is for numeric field 2

return Integer.valueOf(csvLine1.get(2)).compareTo(Integer.valueOf(csvLine2.get(2)));

}

};

Collections.sort(csvLines, comp);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值