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()?
For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation.
Consider lambda expression account -> true . The compiler verifies that the lambda matches Predicate<T> 's boolean test(T) method, which it does--the lambda presents a single parameter ( account ) and its body always returns a Boolean value ( true ). For this lambda, test() is implemented to execute return true; .
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());
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With