Do not allow final variable inside Java 8 Stream

Is there a way to convert the following code to 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);
    }

Java 8 threads complain about missing tmp final variable? Is there any way to solve such situations?

The local variable tmp defined in the enclosing area must be final or effective final

enter image description here

+1
source share
1 answer

First, change the code to use generics and an extended loop for. Assuming valuesthen 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);
}

, , .

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

, , . , ... .

+5

Source: https://habr.com/ru/post/1662253/


All Articles