gpa*_*gpa 1 java foreach java-8 java-stream
我有两种类型的处理实现.不确定为什么流forEach循环抱怨变量'i'必须是final.但如果最终,那么如何解决计算'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);
}
Run Code Online (Sandbox Code Playgroud)
您可以替换forEach用减少.例如:
int i = str.chars()
.filter( c -> c >= 48 && c <= 57 )
.reduce( 0, (a, b) -> a * 10 + (b - 48) );
Run Code Online (Sandbox Code Playgroud)
这里0是初始值,lambda表达式计算新值.a是最新计算的结果,b是流中的下一个元素.实际上,不是使用局部变量来跟踪(累积)最新的计算,而是在减速器内维护累加器.
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |