在Java 8中结合函数和谓词

在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;
    }    
}
最佳答案
你不需要谓词.只需计算总和并检查它是否是> 1000.

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

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

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

转载注明原文:在Java 8中结合函数和谓词 - 代码日志