sec*_*129 5 java java-8 collectors
I am not sure this has been answered earlier or not. Can anyone please tell me what is the problem with third groupBy which I've written ? Why it can not infer ?
class TestGroupBy
{
enum LifeCycle {
ANNUAL, PERENNIAL
}
private String name;
private LifeCycle lifeCycle;
TestGroupBy(String name, LifeCycle lifeCycle) {
this.name = name;
this.lifeCycle = lifeCycle;
}
LifeCycle getLifeCycle() {
return this.lifeCycle;
}
static EnumMap mySupplier() {
return new EnumMap(TestGroupBy.class);
}
public static void main(String[] args) {
List<TestGroupBy> garden = new ArrayList<>();
garden.add(new TestGroupBy("Test1", TestGroupBy.LifeCycle.ANNUAL));
garden.add(new TestGroupBy("Test2", TestGroupBy.LifeCycle.PERENNIAL));
garden.add(new TestGroupBy("Test4", TestGroupBy.LifeCycle.ANNUAL));
garden.add(new TestGroupBy("Test5", TestGroupBy.LifeCycle.PERENNIAL));
// This works
garden.stream()
.collect(Collectors.groupingBy(e -> e.getLifeCycle()));
// This works
garden.stream()
.collect(Collectors.groupingBy(
e -> e.getLifeCycle(),
TestGroupBy::mySupplier,
Collectors.toSet()
));
// This does not work
garden.stream()
.collect(Collectors.groupingBy(
e -> e.getLifeCycle(), // Can not resolve method getLifeCycle()
new EnumMap(TestGroupBy.class),
Collectors.toSet()));
}
}
Run Code Online (Sandbox Code Playgroud)
停止使用原始类型!
这是mySupplier没有原始类型的:
static EnumMap<LifeCycle, Set<TestGroupBy>> mySupplier() {
return new EnumMap<>(LifeCycle.class);
}
Run Code Online (Sandbox Code Playgroud)
an 的键类型EnumMap必须是枚举类型,因此您应该将其LifeCycle用作第一个参数。第二个参数是您在最后使用的收集器返回的内容。您toSet在这里使用过,所以我想您想要一组TestGroupBy.
这就是您的供应商应该是什么样子,具有适当的通用参数和LifeCycle.class作为EnumMap!
现在,您可以这样做:
garden.stream()
.collect(Collectors.groupingBy(
e -> e.getLifeCycle(),
() -> new EnumMap<>(LifeCycle.class),
Collectors.toSet()));
Run Code Online (Sandbox Code Playgroud)
请注意,您必须添加() ->才能使其成为供应商。