Java8 variable in for loop

333 views Asked by At
int sum = a;
int pow = 1;

for (int i = 0; i < n ; i++) {
    sum += b*pow;
    System.out.print(sum+" ");
    pow *= 2;
}

In Java-8 on using Stream gives errors for sum and pow variable that the variable should be final.

1

There are 1 answers

0
Nikolas Charalambidis On

You can use the generated Stream using IntStream and process the numbers in the same way. Note that Math::pow returns Double therefore the pipeline results in DoubleStream.

IntStream.range(0, n).mapToDouble(i -> b * Math.pow(2, i)).reduce(Double::sum);

The only disadvantage is no consumer is available during the reducing, therefore you have to amend it a bit:

IntStream.range(0, n).mapToDouble(i -> b * Math.pow(2, i)).reduce((left, right) -> {
    double s = left + right;
    System.out.println(s);
    return s;
});

To answer this:

In java8 on using stream give the errors for sum and pow variable that the variable should be final.

One of the conditions is that the variables used within lambda expressions must be either final or effectively-final, therefore the mutable operations you used in the for-loop are not allowed and have to be replaced with mapping feature of Streams. This issue is nicely explained at http://ilkinulas.github.io.


Remember, you cannot use the same way you use for-loops.