3

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()?

Malena T
  • 341
  • 2
  • 7
  • 22

3 Answers3

5

Your return statements in forEach method are ignored.

Try to use

boolean exists = key.stream().allMatch(k -> service.existsByKey(k));
contrapost
  • 673
  • 12
  • 22
  • 6
    Even better: `key.stream().allMatch(service::existsByKey);` – Jacob G. Apr 07 '18 at 20:21
  • @JacobG. Agree, but not so readable for one who starts with functional programming and streams. – contrapost Apr 07 '18 at 20:23
  • @contrapost I think it's good to start with method references as early as possible. I find lambdas like `k -> service.existsByKey(k)` much less readable. – lexicore Apr 07 '18 at 21:12
  • @lexicore there is no single answer. Readability is very personal case here. For me, traditional method call with parameter is much more readable than dropping of method parameter with method reference. In my opinion method reference is much like syntactic sugar. You can use it in very limited number of situations. – contrapost Apr 07 '18 at 21:31
1

You cannot return a value with the forEach construct as it accepts a consumer i.e. a function that takes one parameter and returns nothing(void), instead, you can use allMatch as shown in the other answer ornoneMatch like this:

return keys.stream()
           .noneMatch(key -> !service.existsByKey(key))
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You use lambda that is mostly a shortcut for anonymous class. So your code is equivalent to:

    keys.stream().forEach(new Consumer<String>() {
        @Override
        public void accept(String s) {
            boolean exists = service.existsByKey(k);
            if(!exists) return false;
        }
    });

It doesn't return from your method (actually it doesn't compile also).