Java8 thread shortening list of objects with smooth API

Is it possible to shorten the list of objects using a free API method? For example, I have Listof com.mysema.query.types.expr.BooleanExpression, which should be combined using a method com.mysema.query.types.expr.BooleanExpression#and. I can do this using old and reliable ones for everyone, like this, but a little ugly:

BooleanExpression result = predicates.get(0);
for (int i = 1; i < predicates.size(); i++) {
   result = result.and(predicates.get(i));
}

Is it possible to rewrite this through the Java 8 thread API?

+4
source share
1 answer

Yes, you can use the operation reduce:

BooleanExpression result = predicates.stream().reduce(BooleanExpression::and).orElseThrow(AssertionError::new);

This code will reduce all your predicates by and- each intermediate result.

Optional<BooleanExpression>, . , ( .get(0);), AssertionError. , .

, , BooleanExpression true ,

BooleanExpression result = predicates.stream().reduce(identity, BooleanExpression::and);
+5

All Articles