Combining functions and predicates in Java 8

In the isbigorder method, if the total price of the products in the order is greater than 1000, it must return true How do I write it in Java 8? I wrote the sum part, but I couldn't finish it

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 ????;
    }

If other classes are required:

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;
    }    
}

Solution

You don't need predicates Just calculate the sum and check that it is > 1000

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

Or, as Holger commented, when you want to implement a function with a parameter that returns a Boolean value, the predict interface is a more appropriate function interface:

public Predicate<Order> isBigOrder() {
    return o -> o.getProducts()
                 .stream()
                 .mapToLong(Order::getPrice)
                 .sum() > 1000;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>