我试图从逗号分隔文件和MeterID(文件中的第一项)读取日期作为键作为值。但我的问题是,该文件在多行中具有相同的日期,当我尝试将文件读入散列图时,我获得了每个键的额外空值。文件中的数据如下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,,,,请参阅下面的代码,将文件中的数据读入hashmapString 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/028 = 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/028 = 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}
2 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
它应该足够写:
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,1162804],16 / 04/2018 = [1182801],13 / 04/2018 = [1182798]
添加回答
举报
0/150
提交
取消