1 回答
TA貢獻1866條經驗 獲得超5個贊
說真的,使用 for 循環。
int count = 0, sumA = 0, sumB = 0, sumC = 0;
for (Value v : values) {
sumA += v.getA();
sumB += v.getB();
sumC += v.getC();
count++;
}
double avgA = ((double) sumA) / count;
double avgB = ((double) sumB) / count;
double avgC = ((double) sumC) / count;
說真的,使用上面的代碼。
話雖如此,您應該使用上面的代碼,但您可以使用流來完成。
您需要一些值持有者(平均值是 a double,因此您的Value類無法存儲平均值):
class AveragesResult {
public final double a, b, c;
public AveragesResult(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class AveragesIntermediate {
public final double a, b;
public AverageIntermediate(double a, double b) {
this.a = a;
this.b = b;
}
}
現在我們已經有了樣板文件(為了更好地衡量,您應該實現hashCode、equalsand toString,并添加一些 getter),我們終于可以以簡短而緊湊的方式編寫流:
values.stream().collect(teeing(
teeing(averagingInt(Value::getA), averagingInt(Value::getB), AveragesIntermediate::new),
averagingInt(Value::getC),
(ir, avgC) -> new AveragesResult(ir.a, ir.b, avgC));
那不是很難嗎?確保您已靜態導入所有 Collector 函數(所有這些函數看起來都很難看Collectors.)并且您使用的Collectors.teeing是 Java 12(Java 12 中的新增功能)。
不要使用它,使用一個好的舊for循環。
添加回答
舉報
