ariky
ariky

Reputation: 338

Java: How to get a specific row by a given value?(.csv)

Firstly, I don't want any of you to write the code for me. I do not want to be misunderstood. If you just want to give an example, that will be fine.

Let's think I have a csv data table(comma seperated) like:

>Temp     Press      Vf       Vg      Uf      Ug

>50       140        0,5      2,5     1,7     2,6

>60       145        0,502    2,6     1,8     2,68

It will continue for let's say 10 columns and 200 rows. How can I store values of a row column by column? To illustrate I want to get the row which has 60 degree celcius. The other values find by the program and recorded like p1=145, vf1=0.502, Vg1=2.6, Uf1=1.8 ... Note: It is not only for "temp". Maybe the known value is a "Vf" in other case.

I have been searching for 3 days yet I couldn't find the exact same thing that I want. There was always something missing.

Upvotes: 2

Views: 1426

Answers (1)

trylimits
trylimits

Reputation: 2575

Assuming you are not using any API.

Create a class which represents one entry of the CSV file:

public class MyClass {
    private int temp;
    [...]

    public static MyClass createFromCsvEntry(String csvLine) {
        [...]
    }
}

Parse the data of the CSV file and add the single entries to a list. You now can perform the search on these entries:

public class MyClassDao {

    private List<MyClass> data;

    [...] // parsing CSV file and add the entries to data list

    public List<MyClass> searchByTemp(int temp) {
         List<MyClass> result = new ArrayList<>();
         for (MyClass mc : data) {
             if (mc.getTemp().equals(temp)) {
                  result.add(mc);
             }
         }
         return result;
    }

    public List<MyClass> searchByAnyOtherValue(...) {
        [...]
    }
}

Of course if there are other non-functional requirements, such as performance etc., this solution may be not the right choice.

Upvotes: 1

Related Questions