分享一段项目中看到的代码,简单利用函数接口数字的聚合操作
函数接口定义
@FunctionalInterface
public interface BigDecimalOperation {
BigDecimal compute(BigDecimal left, BigDecimal right);
}
聚合方法定义
public static BigDecimal aggregate(BigDecimalOperation method, Object... operands) {
if(operands.length == 0) {
return BigDecimal.ZERO;
}
for(Object op : operands) {
if(op == null) {
throw new IllegalArgumentException();
}
}
int ptr = 0;
BigDecimal[] decimals = new BigDecimal[operands.length];
for(Object op : operands) {
BigDecimal l;
if(op instanceof BigDecimal) {
l = (BigDecimal) op;
} else if(op instanceof Number) {
l = new BigDecimal(((Number) op).doubleValue());
} else {
l = new BigDecimal(op.toString());
}
decimals[ptr++] = l;
}
BigDecimal result = decimals[0];
for(ptr = 1; ptr < decimals.length; ++ptr) {
result = method.compute(result, decimals[ptr]);
}
return result;
}
简单引用
private static BigDecimal subtractDecimals(Object... operands) {
return aggregate(BigDecimal::subtract, operands);
}
private static BigDecimal addDecimals(Object... operands) {
return aggregate(BigDecimal::add, operands);
}