I use google guava predicates and I want to filter it to be able to remove some of them.
For example in this code
Predicates.or(
Predicates.and(p1, p2, Predicates.or(p3, p4)),
Predicates.and(p3, p2, Predicates.or(p1, p4))
Predicates.and(p3, p2, Predicates.or(Predicates.and(p1, p2), Predicates.and(p2, p3)))
);
I want to remove p1
so the result should look like this
Predicates.or(
Predicates.and(p2, Predicates.or(p3, p4)),
Predicates.and(p3, p2, Predicates.or(p4))
Predicates.and(p3, p2, Predicates.or(Predicates.and(p2), Predicates.and(p2, p3)))
);
Is it possible? If yes, how?
Why? We reuse some of predicates with exceptions.
Not after the fact - the Predicate
returned from Predicates.and()
and Predicates.or()
is a black-box, and (by design) provides no way to inspect its component parts.
The right solution is to refactor your code so that you compose this predicate with only the component predicates you intend. One option would be to replace p1
with a alwaysTrue()
or alwaysFalse()
predicate, like so:
Predicate<T> p1OrTrue = p1;
Predicate<T> p1OrFalse = p1;
if (dontUseP1) {
p1OrTrue = Prediactes.alwaysTrue();
p1OrFalse = Predicates.alwaysFalse();
}
Predicates.or(
Predicates.and(p1OrTrue, p2, Predicates.or(p3, p4)),
Predicates.and(p3, p2, Predicates.or(p1OrFalse, p4))
Predicates.and(p3, p2, Predicates.or(Predicates.and(p1OrTrue, p2), Predicates.and(p2, p3)))
);
This means if dontUseP1
is false
then p1
will be incorporated in the composite predicate as before, but if it's true
it will instead be replaced with no-op predicates that cause Predicates.or()
( alwaysFalse()
) and Predicates.and()
( alwaysTrue()
) to rely on the result of the remaining component predicates, making the predicate equivalent to not having p1
at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.