I am trying to convert the following text input file:
A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2
into Map<String, List<String>>
by splitting each line on "="
So far I manged to get this sort of output:
KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2
using such code:
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();
}
How to tweak the above lambda to get something like this:
KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2
Map and collect:
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);
Or map and group by:
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())));
Stream.collect
documentationUse Collectors.mapping
while groupingBy
, for more information look at this 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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With