Search code examples
javaarrayscsvarraylistdouble

How can I convert an ArrayList<String[]> to a double[] that contains decimal values?


I've taken in my inputs using a buffered reader, like so:

private static ArrayList<String[]> dataItem;
private static double[] CONVERT;

public static ArrayList<String[]> readData() throws IOException {
    String file = "numbers.csv";
    ArrayList<String[]> content = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line = "";
        while ((line = br.readLine()) != null) {
            content.add(line.split(","));
        }
    } catch (FileNotFoundException e) { }
    return content;
}

I have a csv file with values like this:

0.2437,0.2235,0.9,0.2599,0.1051,0.1635,0.3563,0.129,0.1015
0.2441,0.3012,0.9,0.1123,0.1079,0.4556,0.4008,0.3068,0.1061
0.2445,0.4806,0.9,0.1113,0.1081,0.354,0.4799,0.3487,0.1034

I want to create a double array (double[]) so I can run through the file one line at a time in my program. How can I take the lines from the file and create this array from them?


Solution

  • Assuming that the CSV data are read successfully into List<String[]>, the conversion to 2D double array may be implemented like this using Stream API:

    static double[][] convert2D(List<String[]> data) {
        return data.stream()
            .map(arr -> Arrays.stream(arr)
                    .mapToDouble(Double::parseDouble).toArray()) // Stream<double[]>
            .toArray(double[][]::new);
    }
    

    If a simple double[] array is needed without keeping the lines, the contents of data may be converted using Stream::flatMapToDouble:

    static double[] convert1D(List<String[]> data) {
        return data.stream()
            .flatMapToDouble(arr -> Arrays.stream(arr)
                    .mapToDouble(Double::parseDouble)) // DoubleStream
            .toArray();
    }