java - 正确使用 Guava 两种类型的谓词

标签 java functional-programming guava predicate

我不确定我是否完全理解 Guava 的Predicate<T>应该使用。我有两个类PromotionCustomer ,并且我想检查哪一项促销 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 ?我什至不知道如何措辞。我是否将“PredicateCustomer 一起使用并将其应用于 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> 。用于测试元素的逻辑(使用 CustomerDateRangeComparator 是函数本身,但输入类型肯定是 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/

相关文章:

java - 将不可变列表传递给 ImmutableList.copyOf()?

java - 发生 EOFException 时返回是否安全

java - 如何在 Maven 中提示用户输入?

android - 如果仅包含在 build.gradle 中,为什么 Android Studio 无法引用库?

functional-programming - "Stack overflow during evaluation"与 stdlib List.map

javascript - 给定一个函数 pipe(foo, bar, baz)(1, 2, 3),你如何实现它等同于 javascript 中的 baz(bar(foo(1,2,3))

java - Guava 先决条件 checkNull、checkArgument

java - 仅当值不存在时如何将其插入到mysql中?

java - RealmList 序列化问题(Realm/Gson/Intent)

构造演算中的递归