javaarrayscsvintgenetic

How can I convert CSV file into an integer array in java?


I have a CSV file including integer numbers :
x.csv

I convert it into an String array:

try (BufferedReader br = new BufferedReader(new FileReader("x.csv"))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split("\n");
            x_values.add(Arrays.asList(values));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

The output is like this : output

but I want to use values as integer numbers and find their average. How can I do that?


Solution

  • You are parsing your lines as String values, not as Integers. Judging from your image your integers are in exponential notation, meaning you would have to parse them first as double, and then cast them to an integer:

        List<Integer> x_values = new ArrayList<>();
    
        try (BufferedReader br = new BufferedReader(new FileReader("x.csv"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split("\n");
                List<Integer> intValues = Arrays.asList(values).stream()
                        .map(Double::parseDouble) // parse x.xxE+02 to xxx.0
                        .map(Double::intValue) // xxx.0 to integer xxx
                        .collect(Collectors.toList()); // back to List
                x_values.addAll(intValues);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    You should make sure though that your csv file only contains integers, otherwise use List<Double> x_values instead and skip the int conversion.