本文主要介绍将Java中,Properties配置文件中配置项通过lambda内容读取到Map<String, List<String>>中的几种方法。

Properties配置文件中内容如下

A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2

1、通过Map和collect来实现

File reqFile = new File("test.config");
try (Stream<String> stream = Files.lines(reqFile.toPath())) {
    Map<String, List<String>> conf = 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);
    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();
}

2、通过map和group by来实现

File reqFile = new File("test.config");
try (Stream<String> stream = Files.lines(reqFile.toPath())) {
    Map<String, List<String>> conf = stream
        .map(s -> Arrays.asList(s.split("=")))
        .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));
    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();
}

相关文档https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-