use*_*773 1 foreach lambda java-8 java-stream
我试图为结果返回一个布尔值.
public boolean status(List<String> myArray) {
boolean statusOk = false;
myArray.stream().forEach(item -> {
helpFunction(item).map ( x -> {
statusOk = x.status(); // x.status() returns a boolean
if (x.status()) {
return true;
}
return false;
});
});
}
Run Code Online (Sandbox Code Playgroud)
lambda表达式中使用的抱怨变量应该是final或者有效的final.如果我指定statusOk,那么我无法在循环内分配.如何使用stream()和map()返回布尔变量?
ΦXo*_*a ツ 13
你正在使用错误的流...
你不需要在流上做foreach,而是调用anyMatch
public boolean status(List<String> myArray) {
return myArray.stream().anyMatch(item -> here the logic related to x.status());
}
Run Code Online (Sandbox Code Playgroud)
Era*_*ran 12
它看起来像helpFunction(item)返回某个具有boolean status()方法的类的一些实例,并且您希望您的方法返回trueif helpFunction(item).status()is truefor your Stream.
您可以使用以下方法实现此逻辑anyMatch:
public boolean status(List<String> myArray) {
return myArray.stream()
.anyMatch(item -> helpFunction(item).status());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12196 次 |
| 最近记录: |