1

I have two type of implementations for processing. Not sure why stream forEach loop complains that variable 'i' must be final. But if final, then how to address issue with logic of computing 'i'?

public static void main(String[] args) {
    String str = "123456789";
    int i = 0;
    //Non Stream
    for (char c : str.toCharArray()) {
        if (c >= 48 && c <= 57) {
            i = i * 10 + (c - 48);
        }
    }
    System.out.println(i);
     i = 0;
    // WHY compiler fails for variable 'i' here? 
    str.chars().forEach((c) -> {
        if (c >= 48 && c <= 57) {
            i = i * 10 + (c - 48);
        }
    });
    System.out.println(i);
}
2
  • 2
    While the meaning of the number constants is derivable from context, there is no reason to use 48 and 57 instead of '0' and '9' Commented Oct 21, 2015 at 18:26
  • good point about character ascii value replacement. Commented Oct 21, 2015 at 18:30

1 Answer 1

5

You can replace the forEach with a reduction. For example:

int i = str.chars()
           .filter( c -> c >= 48 && c <= 57 )
           .reduce( 0, (a, b) -> a * 10 + (b - 48) );

Here, 0 is the initial value and the lambda expression calculates the new value. a is the result of the latest calculation, and b is the next element in the stream. Effectively, rather than using a local variable to track (accumulate) the latest calculation, the accumulator is maintained within the reducer.

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.