Csa*_*rog 4 java lambda local-variables java-8 java-stream
我想在lambda函数中使用局部变量但我得到错误:请参阅代码中的1.和2.点.
class Foo {
int d = 0; // 1. It compiles, but ugly, 2. doesnt compile
public void findMax(List<List<Route>> routeLists) {
int d = 0; // 2.Error : Local variable dd defined in an enclosing scope must be final or effectively final
routeLists.forEach(e-> {
e.forEach(ee -> {
d+=ee.getDistance();
});
});
... doing some other operation with d
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用它们将它们设置为全局变量?
forEach 这是工作的错误工具.
int d =
routeLists.stream() // Makes a Stream<List<Route>>
.flatMap(Collection::stream) // Makes a Stream<Route>
.mapToInt(Route::getDistance) // Makes an IntStream of distances
.sum();
Run Code Online (Sandbox Code Playgroud)
或者只使用嵌套for循环:
int d = 0;
for (List<Route> rs : routeLists) {
for (Route r : rs) {
d += r.getDistance();
}
}
Run Code Online (Sandbox Code Playgroud)
你不能使用 int 作为变量,因为它必须是最终的才能在流中使用。
但是您可以创建一个包装 int 的类。
然后将保存此类的变量声明为final。
更改内部 int 变量的内容。
public void findMax(List<List<Route>> routeLists) {
final IntWrapper dWrapper = new IntWrapper();
routeLists.forEach(e-> {
e.forEach(ee -> {
dWrapper.value += ee.getDistance();
});
});
int d = dWrapper.value;
... doing some other operation with d
}
public class IntWrapper {
public int value;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6916 次 |
| 最近记录: |