Converting a text file to Map<String, List<String>> using lambda

BartD :

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
Michał Ziober :

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())));
  1. Stream.collect documentation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36150&siteId=1