【发布时间】:2018-12-13 19:35:12
【问题描述】:
我有一个示例 csv 文件如下(一个虚拟 csv 文件结构供参考):
Col0, Col1, Col2, Col3, Col4, Col5
str1, str2, str3, str4, str5, 45.545
str1, str2, str3, str4, str5, 45.545
str1, str2, str3, str4, str5, 45.545
str1, str2, str3, str4, str5, 45.545
str1, str2, str3, str4, str5, 45.545
我正在尝试将此 csv 文件读入 HashMap<String, Double>,其中密钥生成为 (Col1 + "|" + Col2 + "|" + Col3 + "|" + Col4 + "|" + Col0) and value as Col5。
我在这里关注了一篇类似的文章 (How to convert csv to a map using Java 8 Stream),但在将 Col5 转换为 double 时出错,如下所示:
java.lang.NumberFormatException: 空字符串
以下是我目前使用的代码:
private void convertCsvtoMap(final String filePath) {
try {
Stream<String> lines = Files.lines(Paths.get(filePath));
Map<String, Double> resMap = lines.skip(1).map(line -> line.split(",")).collect(
Collectors.toMap(line -> (line[1] + "|" + line[2] + "|" + line[3] + "|" + line[4] + "|" + line[0]), line -> Double.parseDouble(line[5])));
} catch (IOException e) {
e.getLocalizedMessage();
}
}
【问题讨论】:
-
使用 this 示例文件我得到一个 different 错误。发布更接近于展示您的问题的示例 CSV。
-
无法判断,因为您的示例文件没有重现问题。找出哪一行给出了异常,您可能会发现问题所在。
标签: java