Converting a text file to Map> using lambd

2020-06-09 04:44发布

问题:

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

回答1:

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


回答2:

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]}


回答3:

If you are open to using a third-party library, the following will work using Eclipse Collections.

ListMultimap<String, String> strings = stream
        .map(s -> s.split("="))
        .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));

Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.

Note: I am a committer for Eclipse Collections.