给定以下代码:
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
的类型键入检查。目前,我可以根据需要获取嵌套 map ,但缺少的是从 Set<Rule>
开始至 Set<TheC>
强>。作为额外的奖励,我还希望整个结构不可变,因为它只代表我的数据的特定 View 。
最佳答案
在 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 - 使用 Java 流和 groupingBy 创建嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59422553/