In the below example , someObjects is a set. I am trying to return true if a condition matches within the loop , however this doesn't seem to compile. However when I just add "return" it works fine.What is the issue that I need to fix?
public boolean find(){
someObjects.forEach(obj -> {
if (some_condition_met) {
return true;
}
});
return false;
}
Compilation Errors
The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( obj) -> {})
I guess you want to do this:
public boolean find(){
return someObjects.stream().anyMatch(o -> your_condition);
}
The forEach
method in a Collection
expects a Consumer
which means a function that takes a value, but doesn't return anything. That's why you can't use return true;
but a return;
works fine.
I you want to break out of the loop when your condition is met, it's better to use a simple for(...)
loop. I assumed that the type of obj
is Object
:
for (Object obj : someObjects) {
if (some_condition_met) {
return true;
}
}
return false;
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