Java 8 list to nested map

只愿长相守 提交于 2020-08-02 07:04:14

问题


I hava a list of Class A like

class A {
 private Integer keyA;
 private Integer keyB;
 private String text;
}

I want to transfer aList to nested Map mapped by keyA and keyB

So I create below code.

Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
    .collect(Collectors.collectingAndThen(Collectors.groupingBy(A::getKeyA), result -> {
        Map<Integer, Map<Integer, List<A>>> nestedMap = new HashMap<Integer, Map<Integer, List<A>>>();
        result.entrySet().stream().forEach(e -> {nestedMap.put(e.getKey(), e.getValue().stream().collect(Collectors.groupingBy(A::getKeyB)));});
        return nestedMap;}));

But I don't like this code.

I think If I use flatMap, I can better code than this.

But I don't know How use flatMap for this behavior.


回答1:


Seems that you just need a cascaded groupingBy:

Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
    .collect(Collectors.groupingBy(A::getKeyA, 
                 Collectors.groupingBy(A::getKeyB)));


来源:https://stackoverflow.com/questions/33644751/java-8-list-to-nested-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!