多次使用流后的java空映射
我正在从csv中的不同列创建两个贴图(以制表符分隔)
oldVal1 newVal1 2
oldVal2 newVal1 3
oldVal3 newVal1 11
.
.
.
最后把它们合并在一起。让我提供一个简单的实现:
public static void main(String[] args) throws FileNotFoundException {
InputStream somefile = new FileInputStream("d:\\dummyfile.csv");
Map<String, String> firstMap = new HashMap<>();
Map<String, String> secondMap = new HashMap<>();
Supplier<Stream<String>> streamSupplier = () -> new BufferedReader(new InputStreamReader(somefile, StandardCharsets.ISO_8859_1)).lines();
firstMap = streamSupplier.get()
.map(p -> p.split("\t"))
.collect(
Collectors.groupingBy(s -> s[1],
Collectors.mapping(g -> g[2],
Collectors.joining(","))));
secondMap = streamSupplier.get().map(p -> p.split("\t"))
.collect(Collectors.toMap(s -> s[0],
s -> s[2]));
firstMap.putAll(secondMap);
}
我面临的问题是第二张地图是空的
期望的输出应该是
Map<String, String>:
oldVal1 -> 2
oldVal2 -> 3
oldVal3 -> 11
newVal1 -> 2,3,11
代码中是否有我遗漏的内容,或者如何解决此问题的其他方法?谢谢你的帮助
# 1 楼答案
您不需要为每个
Map
处理相同的流,而是需要处理单独的流,如下所示:输出:
# 2 楼答案
执行上述代码时,buffereReader为空,因此secondMap未按例外情况填充
只要再读一次inputstream,它就会解决这个问题。或者你可以将其存储到内存中