Java 8 列表到嵌套映射

Java 8 list to nested map

我有一个 Class 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 这种行为。

看来你只需要一个级联 groupingBy:

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