1
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.

4
  • You could use a AtomicInteger instead of regular int to circumvent that issue. Commented Jan 7, 2020 at 20:03
  • 3
    @EdwinDalorzo: It's a workaround as well as a trick with an array, however, wrong by principle. The java-stream provides mechanisms to process such operations. Commented Jan 7, 2020 at 20:45
  • How does your Stream attempt look like? Commented Jan 7, 2020 at 20:46
  • 1
    Seeing AtomicInteger is going to make readers wonder how a simple pipeline is concurrent, and impose another unnecessary performance penalty beyond converting the loop to a stream. I strongly discourage this abuse of the type. Commented Jan 7, 2020 at 23:58

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.