在Java 8 Stream中解决没有最终变量

Sau*_*mar 3 java java-8 java-stream

有没有办法将以下代码转换为Java 8 Stream.

    final List ret = new ArrayList(values.size());
    double tmp = startPrice;
    for (final Iterator it = values.iterator(); it.hasNext();) {
      final DiscountValue discountValue = ((DiscountValue) it.next()).apply(quantity, tmp, digits, currencyIsoCode);
      tmp -= discountValue.getAppliedValue();
      ret.add(discountValue);
    }
Run Code Online (Sandbox Code Playgroud)

Java 8流抱怨没有最终变量tmp?有办法解决这种情况吗?

在封闭范围内定义的局部变量tmp必须是最终的或有效的最终

在此输入图像描述

And*_*eas 7

首先,更改代码以使用泛型和增强for循环.假设values是a List<DiscountValue>,这就是你得到的:

List<DiscountValue> ret = new ArrayList<>(values.size());
double tmp = startPrice;
for (DiscountValue value : values) {
    DiscountValue discountValue = value.apply(quantity, tmp, digits, currencyIsoCode);
    tmp -= discountValue.getAppliedValue();
    ret.add(discountValue);
}
Run Code Online (Sandbox Code Playgroud)

我建议坚持下去,而不是将其转换为流,但如果你坚持,你可以使用单元素数组作为价值持有者.

请注意,只要它们是有效最终的ret,tmp就不必声明final.

List<DiscountValue> ret = new ArrayList<>(values.size());
double[] tmp = { startPrice };
values.stream().forEachOrdered(v -> {
    DiscountValue discountValue = v.apply(quantity, tmp[0], digits, currencyIsoCode);
    tmp[0] -= discountValue.getAppliedValue();
    ret.add(discountValue);
});
Run Code Online (Sandbox Code Playgroud)

如您所见,您没有通过使用流获得任何东西.代码实际上更糟糕,所以...... 不要.