Home > front end >  Java read csv file to list double
Java read csv file to list double

Time:07-30

I cannot convert the CSV file I read into a list. What I want to do is create a List<List<Double>> list. I am creating the same list as below but as List<String>.

My CSV file

-0.140625000000000,0.986816000000000,-0.209473000000000
-0.144531000000000,0.959473000000000,-0.262207000000000
-0.168945000000000,0.945312000000000,-0.340820000000000
-0.141602000000000,0.939453000000000,-0.289551000000000
-0.145508000000000,0.950195000000000,-0.305664000000000
-0.147461000000000,0.946777000000000,-0.302246000000000
-0.146484000000000,0.950684000000000,-0.305176000000000
-0.145996000000000,0.951660000000000,-0.305176000000000
  ....

For Example

List<List<double>> list =  [
   [-0.447266000000000, 0.417969000000000, 0.738770000000000], 
   [-0.447266000000000, 0.417969000000000, 0.738770000000000], 
   [-0.447266000000000, 0.417969000000000, 0.738770000000000], 
   [-0.447266000000000, 0.417969000000000, 0.738770000000000],
   [-0.447266000000000, 0.417969000000000, 0.738770000000000]
]

My code

@RequiresApi(api = Build.VERSION_CODES.N)
public static void main(String[] args) throws IOException, CsvException {

    String fileName = ".../app/src/main/assets/ahmetozkilic.csv";
    try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
        List<String[]> r = reader.readAll();
        List<String> myList = new ArrayList<>();
        r.forEach(x -> myList.add(Arrays.toString(x)));
        System.out.println(myList);
    }
}

CodePudding user response:

Try this :

String fileName =
                ".../app/src/main/assets/ahmetozkilic.csv";
        try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
            List<String[]> r = reader.readAll();
            List<List<Double>> myList = new ArrayList<>();    

            r.forEach(lineArr -> {
                List<Double> line = new ArrayList<>();
                for (String str : lineArr) {
                    line.add(Double.parseDouble(str));
                }
                myList.add(line);
            });
            System.out.println(myList);
        }

CodePudding user response:

You have a couple of different things missing from your code that are necessary to end up with a List<List<double>>.

  1. You are reading Strings but not converting them to double (or Double).
  2. You are reading the original CSV lines as an array instead of a List, but never convert the array to a List.

To solve #1, you can use Double.parseDouble() to convert the Strings to Doubles.

To solve #2, you have to create the final result as a List<List<Double>> instead of List<String>. Then when you loop through the String[], you can convert the strings to Doubles/doubles and add them to the List<Double>.

Since this smells like a homework assignment, I'll leave it to you to write the actual code; these are just the concepts you need.

  • Related