Java 8列表到嵌套映射

时间:2015-11-11 05:26:40

标签: java java-8 java-stream collectors

我有一个类A的列表,如

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

我想将aList转移到由MapkeyA

映射的嵌套keyB

所以我创建了以下代码。

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 个答案:

答案 0 :(得分:14)

似乎您只需要级联groupingBy

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