简体   繁体   中英

Java Stream with ForEach iteration issue

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM