For loop to Java 8 stream foreach()
•
Java
See English answers > break or return from Java 8 stream for each? 11
If any value does not 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 didn't work as expected
keys.stream().forEach(k -> { boolean exists = service.existsByKey(k); if(!exists) return false; });
Did I miss anything? Why not enter (! Exists) staetment in foreach()?
Solution
The return statement in your foreach method will be ignored
Try using
boolean exists = key.stream().allMatch(k -> service.existsByKey(k));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码