使用 lambda 将文本文件转换为 Map<String、List<String>>

2022-09-04 20:17:35

我正在尝试转换以下文本输入文件:

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

答案 1

映射和收集:

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())));
  1. Stream.collect documentation

答案 2

使用 while ,有关详细信息,请查看此带有示例的文档Collectors.mappinggroupingBy

Map<String, List<String>> conf = stream.    
   collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

    System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}

推荐