如何用Java读取CSV文件并将表头及对应列值存储到Map<header, List<values>>中
实现方案
注意你当前代码中CSVReader构造的最后一个参数是
skipLines,如果填1会自动跳过第一行表头,后续csvReader.readNext()读到的会是第一行数据,导致表头丢失,建议修改为0,避免读不到表头。
完整可运行代码
import com.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CsvToMapDemo { // 替换为你实际的CSV文件路径 private static final String filename = "your_csv_file_path.csv"; public static void main(String[] args) throws IOException { // 最后一个参数skipLines设为0,不自动跳行,自行读取表头 CSVReader csvReader = new CSVReader(new FileReader(filename), ',', '"', 0); String[] header = csvReader.readNext(); List<String[]> arr = csvReader.readAll(); Map<String, List<Object>> tableandcols = new HashMap<>(); // 先给每个表头初始化对应的空List,避免后续操作空指针 for (String head : header) { tableandcols.put(head, new ArrayList<>()); } // 循环核心逻辑 for (int i = 0; i < arr.size(); i++) { String[] currentRow = arr.get(i); // 遍历当前行的所有列,通过索引匹配表头和对应列值 for (int colIndex = 0; colIndex < header.length; colIndex++) { String currentHead = header[colIndex]; // 兼容残缺行:如果当前行列数不足,默认存null Object currentValue = colIndex < currentRow.length ? currentRow[colIndex] : null; tableandcols.get(currentHead).add(currentValue); } } System.out.println(tableandcols); csvReader.close(); } }
逻辑说明
- 提前遍历表头数组,给Map中每个表头key都创建空的ArrayList,避免后续往List添加元素时触发空指针异常
- 外层循环遍历所有数据行,拿到单条数据的所有列值
- 内层循环遍历列索引,通过索引匹配表头和对应列的取值,把取值添加到对应表头的List中
- 如果需要把列值转换为Integer、Double等其他类型,可在内层循环中新增类型转换逻辑,再存入List
优化建议
Java 7及以上版本推荐用try-with-resources自动管理流,无需手动调用close方法:
try (CSVReader csvReader = new CSVReader(new FileReader(filename), ',', '"', 0)) { // 所有CSV读取逻辑放在这里 } catch (IOException e) { e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者rajo
相关产品推荐
相关产品推荐

