有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java 8列表到嵌套映射

我有一个类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) 个答案

  1. # 1 楼答案

    似乎您只需要一个级联的groupingBy

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