我尝试将csv文件中的许多值存储到java的结构中(稍后进行计算),但在csv文件中有更多列:id唯一,数据,最高温度,最低温度。
es:
row1 | id1 | 14/09/2016 | 20° | 0 |
row2 | id2 | 14/09/2016 | 25° | 5 |
row3 | id1 | 15/09/2016 | 11° | 2 |
rowN | idN | 16/09/2016 | 14° | 5 |
文件未排序。最后,我导出了计算:
ES:
row1 | id1 | average max | average min |
row2 | id2 | average max | average min |
rowN | idN | average max | average min |
您建议我使用哪种结构?
我希望我很清楚。
答案 0 :(得分:1)
使用Apache Commons CSV,您的代码将是这样的:
class Value {
private int count;
private double sumMaxTemp;
private double sumMinTemp;
Value(double maxTemp, double minTemp) {
this.count = 1;
this.sumMaxTemp = maxTemp;
this.sumMinTemp = minTemp;
}
void add(double maxTemp, double minTemp) {
this.count++;
this.sumMaxTemp += maxTemp;
this.sumMinTemp += minTemp;
}
double getAverageMaxTemp() {
return this.sumMaxTemp / this.count;
}
double getAverageMinTemp() {
return this.sumMinTemp / this.count;
}
}
String input = "id1,14/09/2016,20,0\n" +
"id2,14/09/2016,25,5\n" +
"id1,15/09/2016,11,2\n" +
"idN,16/09/2016,14,5\n";
Map<String, Value> data = new TreeMap<>();
try (CSVParser parser = CSVParser.parse(input, CSVFormat.DEFAULT)) {
for (CSVRecord record : parser) {
String id = record.get(0);
double maxTemp = Double.parseDouble(record.get(2));
double minTemp = Double.parseDouble(record.get(3));
Value value = data.get(id);
if (value == null)
data.put(id, new Value(maxTemp, minTemp));
else
value.add(maxTemp, minTemp);
}
}
NumberFormat format = NumberFormat.getNumberInstance();
try (CSVPrinter printer = new CSVPrinter(System.out, CSVFormat.DEFAULT)) {
for (Entry<String, Value> entry : data.entrySet()) {
Value value = entry.getValue();
printer.printRecord(entry.getKey(),
format.format(value.getAverageMaxTemp()),
format.format(value.getAverageMinTemp()));
}
}
输出
id1,15.5,1
id2,25,5
idN,14,5
答案 1 :(得分:0)
创建一个java类,其属性为csv文件的列,然后将其添加到Linkedlist。