therock24 therock24 - 2 months ago 12
Java Question

Best structure for store values by csv file Java

I try to store many values by csv file into a java's structure (to do the calculations later), but in csv file have more columns : id unique, data, maximum temperature , minimum temperature.

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 |


The file isn't sorted. In the end, I export the calculation:

es:

row1 | id1 | average max | average min |
row2 | id2 | average max | average min |
rowN | idN | average max | average min |


Which structures you advise me to use?

I hope I was clear.

Answer

Using Apache Commons CSV, your code would be something like this:

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()));
    }
}

Output

id1,15.5,1
id2,25,5
idN,14,5
Comments