Reputation: 69
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.
Upvotes: 1
Views: 349
Reputation: 44506
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 java-stream 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 java-stream the same way you use for-loops.
Upvotes: 3