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

Bar*_*rtD 13 java java-8 java-stream

我试图转换以下文本输入文件:

A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2
Run Code Online (Sandbox Code Playgroud)

Map<String, List<String>>通过划分在每一行"="

到目前为止,我想要获得这种输出:

KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2
Run Code Online (Sandbox Code Playgroud)

使用这样的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

如何调整上面的lambda得到这样的东西:

KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2
Run Code Online (Sandbox Code Playgroud)

Mic*_*ber 10

地图和收集:

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);
Run Code Online (Sandbox Code Playgroud)

或者按地图和分组:

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())));
Run Code Online (Sandbox Code Playgroud)
  1. Stream.collect 文件


Dea*_*ool 5

使用Collectors.mappingwhile groupingBy,有关更多信息,请查看此doc-with-example

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]}
Run Code Online (Sandbox Code Playgroud)