如何将CSV文件转换为Java中的整数数组?

n9vozmp4  于 2023-07-31  发布在  Java
关注(0)|答案(2)|浏览(96)

我有一个包含整数的CSV文件:


的数据
我把它转换成一个String数组:

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();
    }

字符串
输出如下:output
但我想用整数的值来求它们的平均值我怎么能做到呢?

qzlgjiam

qzlgjiam1#

您正在将行解析为String值,而不是Integers。从你的图像来看,你的整数是指数符号,这意味着你必须首先将它们解析为double,然后将它们转换为整数:

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();
    }

字符串
你应该确保你的csv文件只包含整数,否则使用List<Double> x_values代替,跳过int转换。

vtwuwzda

vtwuwzda2#

一个稍微现代和简洁的答案

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();
     }

字符串

相关问题