Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value from Java 8 forEach loop

Tags:

java

java-8

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) -> {})

like image 936
Punter Vicky Avatar asked Oct 29 '17 21:10

Punter Vicky


2 Answers

I guess you want to do this:

public boolean find(){
    return someObjects.stream().anyMatch(o -> your_condition);
}
like image 76
Jason Hu Avatar answered Sep 20 '22 11:09

Jason Hu


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;
like image 36
pablochan Avatar answered Sep 21 '22 11:09

pablochan