Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop to Java 8 Stream forEach() [duplicate]

Tags:

java

java-8

I have a for loop for a list that checks whether or not index values exist in the db.

Simply if any value doesn't exist, it immediately returns false.

public boolean exists(List<String> keys) {
     for(String key: keys) {
         boolean exists = service.existsByKey(key);
         if(!exists) return false;
      }
        return true;
}

I tried to change it to java 8 foreach, but it doesn't work as expected.

keys.stream().forEach(k -> {
    boolean exists = service.existsByKey(k);
    if(!exists) return false;
});

Am I missing something? Why doesn't it go in if(!exists) staetment in forEach()?

like image 348
Malena T Avatar asked Jul 08 '26 20:07

Malena T


1 Answers

Your return statements in forEach method are ignored.

Try to use

boolean exists = key.stream().allMatch(k -> service.existsByKey(k));
like image 53
contrapost Avatar answered Jul 11 '26 16:07

contrapost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!