我将csv作为2列的输入,并希望根据日期列(dd / mm / yyyy)对数据进行排序。下面的代码正确排序日期,但我想要与该日期相关的值...此代码的输出类似于
02/05/2012
09/11/2012
10/11/2012
代码:
public static void main(String[] args){
Date value = null;
String reader ="";
String[] input = null ;
Date date;
List<Date> dateList = new ArrayList<Date>();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
File file = new File("data.csv");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while((reader = br.readLine())!=null){
input = reader.split(",");
date = df.parse(input[0]);
dateList.add(date);
}
Collections.sort(dateList, new Comparator<Date>() {
public int compare(Date o1, Date o2){
return o1.compareTo(o2);
}
});
for(Date x : dateList){
System.out.println(df.format(x));
}
} catch (FileNotFoundException fi) {
fi.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(ParseException pe){
pe.printStackTrace();
}
}
答案 0 :(得分:0)
我认为使用对象代表csv的每一行最容易。然后,对这些行进行排序。要获得额外积分,请DateRow
实施可比较。
try块中的相关部分:
BufferedReader br = new BufferedReader(new FileReader(file));
while((reader = br.readLine()) != null) {
input = reader.split(",");
DateRow row = new DateRow(
input,
df.parse(input[0])
);
dateList.add(row);
}
Collections.sort(dateList, new Comparator<DateRow>() {
public int compare(DateRow o1, DateRow o2){
return o1.getKey().compareTo(o2.getKey());
}
});
for (DateRow row: dateList) {
System.out.println(row.getData()[0] + "\t" + row.getData()[1]);
}
DateRow类(如果你希望它是你的主要方法所在的内部类,请保持静态):
private static class DateRow {
private Date key;
private String[] rowData;
public DateRow(String[] rowData, Date key) {
this.rowData = rowData;
this.key = key;
}
public String[] getData() {
return this.rowData;
}
public Date getKey() {
return this.key;
}
}