【问题标题】:Java 8 list to nested mapJava 8 列表到嵌套映射
【发布时间】:2016-02-12 04:50:38
【问题描述】:

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

【问题讨论】:

    标签: java java-8 java-stream collectors


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2017-05-25
      • 2019-10-07
      • 2020-04-02
      • 2018-04-21
      相关资源
      最近更新 更多