gpt4 book ai didi

java - 使用 Java 流和 groupingBy 创建嵌套 map

转载 作者:行者123 更新时间:2023-11-29 06:48:12 24 4
gpt4 key购买 nike

给定以下代码:

  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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com