使用Lambda将文本文件转换为Map <string,list <string =“” >>

时间:2019-01-26 22:43:25

标签: java java-8 java-stream

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

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

3 个答案:

答案 0 :(得分: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);

或通过以下方式进行地图和分组:

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

答案 1 :(得分:5)

Collectors.mapping时使用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]}

答案 2 :(得分:2)

如果您愿意使用第三方库,则可以使用Eclipse Collections使用以下程序。

ListMultimap<String, String> strings = stream
        .map(s -> s.split("="))
        .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));

Collectors2.toListMultimap使用Function来计算密钥,并使用单独的Function来计算值。 ListMultimap<K, V>类型等效于Map<K, List<V>>

注意:我是Eclipse Collections的提交者。

相关问题