简体   繁体   中英

Creating nested maps with Java stream and groupingBy

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM