问题
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