Java 8列表到嵌套映射

Chu*_*rap 9 java java-8 java-stream collectors

我有一个A类似的列表

class A {
 private Integer keyA;
 private Integer keyB;
 private String text;
}
Run Code Online (Sandbox Code Playgroud)

我想转移aList到嵌套Map映射由keyAkeyB

所以我创建下面的代码.

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;}));
Run Code Online (Sandbox Code Playgroud)

但我不喜欢这段代码.

我想如果我使用flatMap,我可以更好地编码.

但我不知道如何使用flatMap这种行为.

Tag*_*eev 14

似乎你只需要一个级联groupingBy:

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