我不确定我是否完全理解 Guava 的Predicate<T>
应该使用。我有两个类Promotion
和Customer
,并且我想检查哪一项促销 Activity 适用于客户。
public Optional<Promotion> getApplicablePromotionToCustomer(final List<Promotion> activePromotions,
final Customer customer) {
return FluentIterable.from(activePromotions).firstMatch(new Predicate<Promotion>() {
@Override
public boolean apply(final Promotion input) {
return input.getCustomerType().equals(customer.getType()) && new DateRangeComparator().overlaps(input.getDateRange(), customer.getDateRange());
}
});
}
我的问题与正确输入 Predicate
有关。 Predicate
是否正确类型 Promotion
或者我应该用 Promotion
构建一个包装类和Customer
?我什至不知道如何措辞。我是否将“Predicate
与 Customer
一起使用并将其应用于 Promotion
”?
如果我想提取 Predicate
的匿名实现对于它自己的类,我必须让构造函数采用 Customer
,甚至是 DateRangeComparator
如果想让它可定制。这是很好还是方法完全错误?
最佳答案
Is it correct to make Predicate of type Promotion or should I build a wrapper class with Promotion and Customer?
是的,这是正确的。您要实现的过滤功能的形式为 f(x) = y
哪里y
属于{false, true}
。
这里的类型是 x
是要应用该函数的元素的类型(即 Predicate
的类型)。由于您过滤了 List<Promotion>
谓词的类型将为 Predicate<Promotion>
。用于测试元素的逻辑(使用 Customer
和 DateRangeComparator
是函数本身,但输入类型肯定是 Promotion
。
Am I using a "Predicate with a Customer and applying it to a Promotion"?
每个人都有自己的措辞,只要你说清楚就行,我想这并不重要。但是,是的,您将谓词应用于 Promotion
。
If I want to extract the anonymous implementation of Predicate to it's own class, I'll have to make the constructor take a Customer, and even a DateRangeComparator if want to make that customizable. Is this fine or approach is totally wrong?
是的,这样做没有什么错。我唯一要记住的是,您应该尽可能尝试实现无状态谓词,即不保留过滤内容的谓词,以便可以独立处理每个项目。当您开始进行并行计算时,这非常有用,因为必须测试的每个对象都可以使用谓词作为独立的“盒子”。
关于java - 正确使用 Guava 两种类型的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31608653/