Creating nested maps with Java stream and groupingBy

孤街浪徒 提交于 2021-01-29 12:52:07

问题


Given the following code:

  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;
  }

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.


回答1:


Use Collector.mapping with Collectors.toSet downstream :

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()))));
}


来源:https://stackoverflow.com/questions/59422553/creating-nested-maps-with-java-stream-and-groupingby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!