Collect Lines using Multimap Collector

2020-03-20 01:43发布

问题:

Is there a way to covert the below to using collectors yet?

List<String[]> lines = getLines();

Multimap<String,String> multimap = ArrayListMultimap.create();

lines.forEach(line -> 
multimap.put(line[0],line[1]);
);

回答1:

You can use Multimaps.toMultimap collector:

ListMultimap<String, String> multimap = lines.stream()
        .collect(Multimaps.toMultimap(
                l -> l[0],
                l -> l[1],
                ArrayListMultimap::create
        ));

Or if you don't need mutability, use ImmutableListMultimap.toImmutableListMultimap collector:

ListMultimap<String, String> multimap = lines.stream()
        .collect(toImmutableListMultimap(l -> l[0], l -> l[1]));