问题
I am trying to return a boolean for the result.
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;
});
});
}
It's complaining variable used in lambda expression should be final or effectively final. If I assign statusOk, then I couldn't assign inside the loop. How can I return a boolean variable using stream() and map()?
回答1:
you are using the stream wrong...
you dont need to do a foreach on the stream, invoke the anyMatch instead
public boolean status(List<String> myArray) {
return myArray.stream().anyMatch(item -> here the logic related to x.status());
}
回答2:
It looks like helpFunction(item)
returns some instance of some class that has a boolean status()
method, and you want your method to return true
if helpFunction(item).status()
is true
for any element of your Stream
.
You can implement this logic with anyMatch
:
public boolean status(List<String> myArray) {
return myArray.stream()
.anyMatch(item -> helpFunction(item).status());
}
来源:https://stackoverflow.com/questions/47746443/java-how-to-use-stream-map-to-return-boolean