在Java 8中结合函数和谓词

时间:2018-01-22 12:29:09

标签: java java-8 functional-programming predicate functional-interface

isBigOrder方法中,如果订单中产品的总价格大于1000,则必须返回true。我怎么用java 8编写它?我写了总和部分,但我无法完成它。

public Function<Order, Boolean> isBigOrder() {

        Function<Order, Optional<Long>> sum = a -> a.getProducts()
                .stream()
                .map(P -> P.getPrice())
                .reduce((p1,p2)->p1+p2);

        Predicate <Optional<Long>> isBig =  x -> x.get() > 1000 ;

        return ????;
    }

如果需要其他课程:

enum OrderState { CONFIRMED, PAID, WAREHOUSE_PROCESSED, READY_TO_SEND, DELIVERED }

enum ProductType { NORMAL, BREAKABLE, PERISHABLE }

public class Product {
    private String code;
    private String title;
    private long price;
    private ProductState state;
    private ProductType type;

    //all fields have getter and setter

    public Product price(long price) {
        this.price = price;
        return this;
    }
}

public class Order {

    private String code;
    private long price;
    private String buyyer;
    private OrderState state;
    private List<Product> products = new ArrayList<>();

    //all fields have getter and setter

    public Order price(long price) {
        this.price = price;
        return this;
    }

    public Order product(Product product) {
        if (products == null) {
            products = new ArrayList<>();
        }
        products.add(product);
        return this;
    }    
}

2 个答案:

答案 0 :(得分:8)

您不需要Predicate。只需计算总和并检查它是否&gt; 1000.

public Function<Order, Boolean> isBigOrder() {
    return o -> o.getProducts()
                 .stream()
                 .mapToLong(Product::getPrice)
                 .sum() > 1000;
}

或者,正如Holger所评论的那样,Predicate接口是一个更合适的函数接口,当你想用一个返回boolean的参数实现一个函数时:

public Predicate<Order> isBigOrder() {
    return o -> o.getProducts()
                 .stream()
                 .mapToLong(Order::getPrice)
                 .sum() > 1000;
}

答案 1 :(得分:5)

假设您无法在写作状态下组合这两个函数,例如,因为它们来自不同的地方,您可以按如下方式组合它们:

public static Function<Order,Boolean> combine(
    Function<Order, Optional<Long>> f
,   Predicate <Optional<Long>> pred
) {
    return a -> pred.test(f.apply(a));
}