Solve no final variable inside Java 8 Stream

99封情书 提交于 2019-12-03 18:29:39

First, change the code to use generics and an enhanced for loop. Assuming values is then a List<DiscountValue>, this is what you get:

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);
}

I'd suggest staying with that, and not convert it to streams, but if you insist, you can use a one-element array as a value-holder.

Note that ret and tmp doesn't have to be declared final, as long as they are effectively-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);
});

As you can see, you haven't gained anything by using streams. The code is actually worse, so ... don't.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!