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();
}