I'm currently tackling with the issue of transforming for loops which use bitwise operations using Lambdas in Java 8.
Given a set of complex entries, it's required for the loop to traverse ALL entries and call a given method on them (method returns boolean value). Afterwards, return the result.
In other words, I need to call the method on all entries and store the result. The reason behind this is that each entry independently performs a complex operation and must be performed. The end result is a combination of results.
Code snippet:
boolean areAllSuccessful = true;
for (SomeEntry entry : entries) {
areAllSuccessful = areAllSuccessful & entry.doComplexAction(); // keep calling the method on other entries regardless of the result.
}
return areAllSuccessful;
The problem is that the Lambda Functions in Java 8 usually perform short-circuit operations (once the false entry has been detected, the "loop" breaks and the false result is returned).
My best solution so far was to use map/filter/count combination:
return entries
.stream()
.map(entry -> entry.doComplexAction())
.filter(result -> result == false)
.count() > 0
Is there a smarter/cleaner way of doing this?
Thanks!
forloops than for streams. Really, trying to make everything be stream-based is not the way to go. If it works as it is, then leave it that way. - fpsisSuccessful()is a really bad name for a method with side-effects that makes lots of operations. You should 1) make clear in the question that the method has side-effects and thus needs to be called on every entry, and 2) rename the method to something likedoComplexActions(). - walenentry.isSuccessful() && areAllSuccessful) to force the method to execute. Don't use screwdrivers to hammer nails. You'll just confuse everyone. Also, don't put a long comment at the end of the line where it'll go off the screen and devs won't read it. Put it on its own line before the line it annotates. - jpmc26