使用Java流和分组创建嵌套地图 [英] Creating nested maps with Java stream and groupingBy

查看:58
本文介绍了使用Java流和分组创建嵌套地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

  private enum TheA {
    AA,
  }

  private class TheB {
    String b;
  }

  private enum TheC {
    CC,
  }

  private class Rule {
    TheA a;
    TheB b;
    TheC c;

    public TheA getA() {
      return a;
    }

    public TheB getB() {
      return b;
    }

    public TheC getC() {
      return c;
    }
  }

  private Map<TheA, Map<TheB, Set<TheC>>> createView(Set<Rule> rules) {
    Map<TheA, Map<TheB, List<Rule>>> value =
        rules.stream().collect(groupingBy(Rule::getA, groupingBy(Rule::getB)));
    return value;
  }

我希望createView的类型进行检查.目前,我可以根据需要获取嵌套地图,但是缺少的是从 Set<Rule>Set<TheC> .作为额外的奖励,我还希望整个结构是不变的,因为它仅代表数据的特定视图.

I want the types of createView to type check. Currently, I am able to get the nested maps as I want but what is missing is to go from Set<Rule> to Set<TheC>. As an extra bonus, I would also want this whole structure to be immutable since it's only representing a specific view of my data.

推荐答案

Collectors.toSet下游使用Collector.mapping:

private Map<TheA, Map<TheB, Set<TheC>>> createView(Set<Rule> rules) {
    return rules.stream().collect(groupingBy(Rule::getA,
            groupingBy(Rule::getB, mapping(Rule::getC, toSet()))));
}

这篇关于使用Java流和分组创建嵌套地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆