我正在尝试转换以下文本输入文件:
A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2
进入Map<String, List<String>>
通过在 "="
上拆分每一行
到目前为止,我设法获得了这种输出:
KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2
使用这样的代码:
File reqFile = new File("test.config");
try (Stream<String> stream = Files.lines(reqFile.toPath())) {
Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));
for (Map.Entry<String, List<String>> entry: conf.entrySet()) {
System.out.println("KEY: " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println("VALUE: " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
如何调整上面的 lambda 以获得这样的结果:
KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2
最佳答案
map 和收集:
Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(HashMap::new,
(map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
HashMap::putAll);
或者映射和分组依据:
Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));
关于java - 使用 lambda 将文本文件转换为 Map<String, List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383490/