Javad Akbari
Javad Akbari

Reputation: 95

Combine a Function and a Predicate in Java 8

In isBigOrder method if sum prices of products in order is bigger than 1000 it must return true. how can I write it using java 8? I wrote the sum part but I couldn't complete 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 ????;
    }

In case other classes are needed:

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

Upvotes: 3

Views: 2852

Answers (2)

Eran
Eran

Reputation: 394146

You don't need the Predicate. Just calculate the sum and check whether it's > 1000.

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

Or, as Holger commented, the Predicate interface is a more suitable functional interface when you want to implement a function with a single argument that returns a boolean:

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

Upvotes: 9

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Assuming that you cannot combine the two functions at the state of writing, for example, because they come from different places, you could combine them as follows:

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

Upvotes: 5

Related Questions