简体   繁体   English

从嵌套结构中删除谓词(Google番石榴谓词)

[英]Remove predicate from nested structure (google guava predicates)

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 我想删除p1所以结果应如下所示

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. 事后不-的Predicate从返回Predicates.and()Predicates.or()是一个黑盒子,和(设计)提供了没有办法检查它的组成部分。

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: 一种选择是将p1替换为alwaysTrue()alwaysFalse()谓词,如下所示:

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. 这意味着如果dontUseP1falsep1将像以前一样被合并到复合谓词中,但是如果为true ,它将被导致Predicates.or()alwaysFalse() )和Predicates.and()无操作谓词代替。 ( alwaysTrue() )依靠其余成分谓词的结果,使谓词等效于根本没有p1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM