The Java 8 stream aggregates a map

I tried to do something that seemed straightforward, but so far I have no luck I have a list of maps from a bunch of parallel completable futures, and the results must be added Since the keys in the mapping are unique, you need to merge values and generate a new mapping of unique keys associated with the combination list of sometype For example:

Map 1: key1: sometype1 key2: sometype2

MAP2 key1:Sometype3 key2:Sometype4

Expected final results: map3: key1: sometype, sometype3, key2: sometype2, sometype4

I try to use groupby and other methods, but it seems that most people assume to start with list instead of map, so I can't find a direct way to do this

So far I have something similar:

Map<String,List<Sometype>> volPercent = waitGroup.stream()
            .map(CompletableFuture::join)
            .flatMap((e) -> e.entrySet().stream())
            .collect(Collectors.groupingBy());

I'm not sure what needs grouping I tried map Entry:: getKey, but it is not compiled:

Error:(69,25) java: incompatible types: inference variable T has incompatible bounds
equality constraints: com.sometype
lower bounds: java.util.Map.Entry<java.lang.String,com.sometype>

Solution

I suppose you start with a set of maps:

Stream<Map<String,Sometype>> input = ... ;

You go a long way in floor plans and collection But the code you tried,

input.flatMap(map -> map.entrySet().stream())
         .collect(Collectors.groupingBy(Map.Entry::getKey));

It provides you with a mapping, whose key is string, and its value is the list of mapping entries, especially list < map Entry < string, type > > instead of list < type > as you wish What you need to do is use the "downstream" function of the collector after key grouping You want to get each map Entry and extract (map) it to its value, that is, sometype This is done through the mapping collector

Now, you may have set up several sometype instances for each key, so you need to collect them into the list This is done using another downstream collector, which collects them into a list This is done using the familiar tolist () collector

The final code is as follows:

Map<String,List<Sometype>> result =
    input.flatMap(map -> map.entrySet().stream())
         .collect(groupingBy(Map.Entry::getKey,mapping(Map.Entry::getValue,toList())));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>