简体   繁体   English

Java Stream与ForEach迭代问题

[英]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. 不确定为什么stream forEach循环会抱怨变量'i'必须是最终变量。 But if final, then how to address issue with logic of computing 'i'? 但是如果是最终的,那么如何解决计算“ 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 . 您可以替换forEach减少 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. 此处, 0为初始值,lambda表达式计算新值。 a is the result of the latest calculation, and b is the next element in the stream. a是最新计算的结果, b是流中的下一个元素。 Effectively, rather than using a local variable to track (accumulate) the latest calculation, the accumulator is maintained within the reducer. 有效地,不是使用局部变量来跟踪(累加)最新的计算,而是将累加器维护在减速器内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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