Java Streams: get values grouped by inner map key

岁酱吖の 提交于 2019-12-04 23:27:50

Your Stream is composed of Map.Entry objects but want you want to collect is actually the value of the entry, not the entry itself. With your current code, you would be obtaining a Map<B, List<Map.Entry<B, C>>>.

As such, you are just missing a call to Collectors.mapping. This collector will map the Stream element with the given mapper function and collect that result into the downstream container. In this case, the mapper is Map.Entry::getValue (so returning the value from the map entry) and the downstream collector collects into a List.

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,
                 Collectors.mapping(Map.Entry::getValue, Collectors.toList())
            ));
}

Your stream pipeline returns a Map<B, List<Map.Entry<B,C>>>, not a Map<B, List<C>>.

To get what a Map<B, List<C>>, you need to add a mapping that would map Map.Entry<B,C> to C :

return input.entrySet()
        .stream()
        .flatMap(it -> it.getValue().entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey,Collectors.mapping(Map.Entry::getValue,Collectors.toList())));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!