我想对Numbers列表进行总和聚合。我想使用泛型来做,因为我们将使用不同的聚合函数。
这就是我想要的(更少):
SumAggregator<Double, Double> sumAggregatorDouble = new SumAggregator<>();
Double sumDouble = AggregatorUtils.aggregate(elements, sumAggregatorDouble);
SumAggregator<Integer, Integer> sumAggregatorInteger = new SumAggregator<>();
Integer sumInteger = AggregatorUtils.aggregate(elements, sumAggregatorInteger);
MinAggregator<Integer, Integer> minAggregatorInteger = new MinAggregator<>();
Integer minInteger = AggregatorUtils.aggregate(elements, minAggregatorInteger);
我想从所有Aggregator
类实现一个Aggregator
接口。
我可以这样做吗?也许有人知道该怎么做,或者更好的方式来做我想做的事。
编辑:这是我试过的
public class SumAggregator<I extends Number, O extends Number> implements Aggregator<I, O> {
// Attributes
private O count;
// Constructors
public SumAggregator() {
this.count = 0.0;
}
@Override
public O apply(I input) {
count = count + input; // The operator + is undefined for the argument type(s) Double, I
return count; // Error: Type mismatch
}
@Override
public O getResult() {
return count; // Error: Type mismatch
}
}