Like And all booleans on a list using lambdas?

I have a list of objects from which I extract logical values ​​and want to apply operation I to them. Is there a better (or more concise) way to do this?

final boolean[] result = {true};
someList.stream().map(o -> o.getBooleanMember()).forEach(b -> result = result && b);
+4
source share
2 answers

You can use reduce:

boolean result = someList.stream().map(o -> o.getBooleanMember()).reduce(true,(a,b)->a&&b);
+7
source

If you have org.apache.commons in your dependencies, you can use a class from a mutable package:

org.apache.commons.lang3.mutable.MutableBoolean

You can then change this value inside your anonymous functions (lambdas) as follows:

    List<YourClass> someList = new ArrayList<>();
    MutableBoolean result = new MutableBoolean(true);
    someList.stream().map(YourClass::getBooleanMember).forEach(b -> result.setValue(result.getValue() && b));

If you do not have this dependency, you can create your own shell.

+1
source

All Articles