Vhd. h
Vhd. h

Reputation: 3

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?

Upvotes: 0

Views: 3097

Answers (2)

Bob Wojack
Bob Wojack

Reputation: 33

A slightly more modern and concise answer

     List<Integer> x_values = new ArrayList<>();

     try (BufferedReader br = Files.newBufferedReader(Paths.get("x.csv"))) {
         List<Integer> intValues = br.lines()
                 .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();
     }

Upvotes: 0

T A
T A

Reputation: 1756

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.

Upvotes: 1

Related Questions