Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 436
BartD Avatar asked Jan 26 '19 22:01

BartD


2 Answers

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
like image 104
Michał Ziober Avatar answered Sep 24 '22 02:09

Michał Ziober


Use 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]}
like image 35
Deadpool Avatar answered Sep 25 '22 02:09

Deadpool