Java streams: get value groups through internal map keys

I have map < A, map < B, C > > and I want to get map < B, list < C > > from it using java streams

I tried to do this:

public <A,B,C> Map<B,List<C>> groupsByInnerKey(Map<A,Map<B,C>> input) {
    return input.values()
            .stream()
            .flatMap(it -> it.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey));
}

What do I expect

>Flatmap gives a stream of stream Entry < B, C > > collect (collectors. Groupingby (...)) gets and applies to map Function of entry < B, C > And returns B, so it collects the value of C into list < C >

But it doesn't compile. Literally:

Map in the last line Entry :: getKey.

Can someone explain what is wrong and what is the right way to achieve what I want?

Solution

Your stream is created by map The entry object, but you want to collect the value of the entry, not the entry itself Using your current code, you will get a map < B, list < map Entry< B>>>>>.

Therefore, you just want to call collectors mapping. The collector maps the stream element to the given mapper function and collects the result into the downstream container In this case, the mapper is map Entry:: getValue (so the value is returned from the map entry), and the downstream collector collects it into the list

public <A,C>> input) {
    return input.values()
            .stream()
            .flatMap(it -> it.entrySet().stream())
            .collect(Collectors.groupingBy(
                 Map.Entry::getKey,Collectors.mapping(Map.Entry::getValue,Collectors.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
分享
二维码
< <上一篇
下一篇>>