Java 8 Lambdas - Bitwise AND Operations

xanmcgregor :

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!

Eugene :

Shouldn't that look something like this:

boolean areAllSuccessful = entries.stream()
   .map(entry -> entry.isSuccessful())
   .reduce(Boolean.TRUE, Boolean::logicalAnd);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448997&siteId=1