You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取CSV文件并转换为List<List<Double>>的问题

问题描述

我没法把读取的CSV文件转换成目标列表,想要创建List<List<Double>>类型的列表,但现在只能得到List<String>类型的列表。

我的CSV文件内容示例:

-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
....

期望得到的列表结构:

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]
]

我的现有代码:

@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);
    }
}
解决方案

要实现List<List<Double>>,需要把每一行的字符串数组转换成Double类型的列表,而非直接转成字符串存入列表。修改后的代码如下:

@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[]> rows = reader.readAll();
        List<List<Double>> resultList = new ArrayList<>();
        
        for (String[] row : rows) {
            List<Double> doubleRow = new ArrayList<>();
            for (String numStr : row) {
                // 去除可能存在的空格,转换为Double类型
                double num = Double.parseDouble(numStr.trim());
                doubleRow.add(num);
            }
            resultList.add(doubleRow);
        }
        
        // 打印验证结果
        System.out.println(resultList);
    }
}

关键说明

  • 遍历读取到的每一行字符串数组,将每个字符串元素去除空格后,通过Double.parseDouble()转换为Double类型
  • 把转换后的Double元素存入子列表,再将子列表加入最终的结果列表
  • 如果CSV中存在空值或非数字内容,需额外添加异常处理逻辑(比如用try-catch包裹转换步骤)

内容的提问来源于stack exchange,提问作者Ayse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:54:38