小编Chu*_*rap的帖子

Java 8列表到嵌套映射

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

java java-8 java-stream collectors

9
推荐指数
1
解决办法
2731
查看次数

标签 统计

collectors ×1

java ×1

java-8 ×1

java-stream ×1