Java 8列表转嵌套映射

13

我有一个类别为A的列表,例如:

class A {
 private Integer keyA;
 private Integer keyB;
 private String text;
}
我想将aList转换为由keyAkeyB映射的嵌套Map。因此,我创建了以下代码。
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;}));

但我不喜欢这段代码。

我认为,如果我使用flatMap,我可以写出比这更好的代码。

但我不知道如何在此情况下使用flatMap

1个回答

26

看起来你只需要一个级联的groupingBy

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接