gpt4 book ai didi

java - 将逗号分隔的文本文件读取到 HashMap 中,其中文件在多行中具有相同的键 Java

转载 作者:行者123 更新时间:2023-12-02 09:54:24 24 4
gpt4 key购买 nike

我正在尝试从逗号分隔的文件中读取日期作为键,并将 MeterID(文件中的第一项)作为值读取。但我的问题是,该文件在多行中具有相同的日期,当我尝试将文件读入 HashMap 时,每个键都会获得额外的空值。

文件中的数据如下

MeterID,ServiceLocationID,ESIID,ReadingDate,ReadingTime,kWh,rxKWh,KVARHImprt,KVARhExprt,kWhImprtRateA,kWhImprtRateB,kWhExprtRateA,kWhExprtRateB,kVARhImprtRateA,kVARhImprtRateB,kVARhExprtRateA,kVARhExprtRateB,kVARhTotalRateA,kVARhTotalRateB,ExprtkVARhTotalRateA,ExprtkVARhTotalRateB
1182798,,,13/04/2018,12:00:00AM,12391.000,0.000,,,6196.991,6194.366,0.074,0.000,1119.000,1132.000,0.000,0.000,,,,
1182799,,,14/04/2018,12:00:00AM,690.000,0.000,,,348.468,342.449,0.074,0.000,95.000,96.000,0.000,0.000,,,,
1182800,,,15/04/2018,12:00:00AM,2863.000,0.000,,,1133.865,1729.365,0.074,0.000,37.000,21.000,156.000,135.000,,,,
1182801,,,16/04/2018,12:00:00AM,1578.000,0.000,,,1065.586,512.603,0.074,0.000,225.000,199.000,27.000,14.000,,,, 1182802,,,17/04/2018,12:00:00AM,2059.000,0.000,,,716.310,1343.338,0.074,0.000,58.000,85.000,63.000,78.000,,,,
1182803,,,18/04/2018,12:00:00AM,1824.000,0.000,,,755.363,1069.038,0.074,0.000,234.000,289.000,65.000,73.000,,,, 1182804,,,18/04/2018,12:00:00AM,1824.000,0.000,,,755.363,1069.038,0.074,0.000,234.000,289.000,65.000,73.000,,,,

请参阅下面的代码,将文件中的数据读取到 HashMap 中

String filePath = "electric-enhanced_0000_201804130555.txt";
String delimiter = ",";
HashMap<String, String> map = new HashMap<>();

try (Stream<String> lines = Files.lines(Paths.get(filePath)).skip(1)) {
lines.filter(line -> line.contains(delimiter)).forEach(line -> map.put(line.split(delimiter)[3],
line.split(delimiter)[0] + "," + map.get(line.split(delimiter)[3])));
}

System.out.println(map);

异常结果是

{15/04/2018=1182800, 14/04/2018=1182799, 17/04/2018=1182802, 18/04/2018=1182804,1182803, 16/04/2018=1182801, 13/04/2018=1182798}

实际结果是 - 我想要排除的每个键都带有 null

{15/04/2018=1182800,null, 14/04/2018=1182799,null, 17/04/2018=1182802,null, 18/04/2018=1182804,1182803,null, 16/04/2018=1182801,null, 13/04/2018=1182798,null}

最佳答案

这样写就足够了:

lines.stream().filter(line -> line.contains(delimiter)).forEach(line -> map.put(line.split(delimiter)[3],
line.split(delimiter)[0]));

您可能还想将 HashMap 替换为 org.apache.commons.collections.map.MultiValueMap,这样您就可以在同一键下存储多个值.

所以:

Map<String, String> map = new MultiValueMap();

我在您的测试数据中添加了一行,现在日期 18/04/2018 出现了两次,输出如下{15/04/2018=[1182800]、14/04/2018=[1182799]、18/04/2018=[1182803, 1182804]、16/04/2018=[1182801], 13/04/2018=[1182798]}

关于java - 将逗号分隔的文本文件读取到 HashMap 中,其中文件在多行中具有相同的键 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com