java csv排序,在java中按升序对csv文件中的一列数据排序

import java.io.*;

import java.util.*;

public class Sort {

public static void main(String[] args) throws Exception {

BufferedReader reader = new BufferedReader(new FileReader("data1.csv"));

Map map=new TreeMap();

String line="";

while((line=reader.readLine())!=null){

map.put(getField(line),line);

}

reader.close();

FileWriter writer = new FileWriter("sorted_numbers.txt");

for(String val : map.values()){

writer.write(val);

writer.write('\n');

}

writer.close();

}

private static String getField(String line) {

return line.split(",")[0];//extract value you want to sort on

}

}

Hia

I am trying to read a unsorted file and get Java to sort one column of the csv data file and print those results in a new file. I borrowed this solution whilst I was searching on this website because I think it is ideal for what I am trying to acomplish. I have a 282 rows of data in the form of

UserID, Module, Mark

Ab004ui, g46PRo, 54

cb004ui, g46GRo, 94

gy004ui, g46GRo, 12

ab004ui, g46PRo, 34

this is in the csv file.

when I use the above code it only gives me one line in the sorted_marks.txt, like this

ab004ui, g46PRo, 34

and I believe it wasnt even sorted.

I want all the results from the new file to be sorted based on their userID and nothing else but I can't seem to get it to work, please any help would be greatful

解决方案

Remove the new lines from data1.csv.

I would prefer to use the second generic String of the Map as a list of string and everything is almost same like below

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.TreeMap;

public class Sort {

public static void main(String[] args) throws Exception {

BufferedReader reader = new BufferedReader(new FileReader("data1.csv"));

Map> map = new TreeMap>();

String line = reader.readLine();//read header

while ((line = reader.readLine()) != null) {

String key = getField(line);

List l = map.get(key);

if (l == null) {

l = new LinkedList();

map.put(key, l);

}

l.add(line);

}

reader.close();

FileWriter writer = new FileWriter("sorted_numbers.txt");

writer.write("UserID, Module, Mark\n");

for (List list : map.values()) {

for (String val : list) {

writer.write(val);

writer.write("\n");

}

}

writer.close();

}

private static String getField(String line) {

return line.split(",")[0];// extract value you want to sort on

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值