小编Jav*_*ari的帖子

在Java8中组合两个函数

isReadyToDeliver方法中,如果订单中的所有产品都可用(ProductState.AVAILABLE)并且订单状态已准备好发送(OrderState.READY_TO_SEND),则方法必须返回true.我写了两部分,但我无法将它们组合在一起,

我写了,return orderState.andThen(productState)但得到这个错误:

andThen(Function<? super Boolean,? extends V>)类型中的方法Function<Order,Boolean>不适用于参数(Function<Order,Boolean>)

public class OrderFunctions  {

    public Function<Order, Boolean> isReadyToDeliver() {            
        Function<Order, Boolean> orderState = o -> o.getState() == OrderState.READY_TO_SEND;            
        Function<Order, Boolean>  productState = 
                o -> o.getProducts()
                    .stream()
                    .map(Product -> Product.getState())
                    .allMatch(Product -> Product == ProductState.AVAILABLE);

        return ????? ; 
       //return  orderState.andThen(productState);
       //error: The method andThen(Function<? super Boolean,? extends V>) in the type Function<Order,Boolean> is not applicable for the arguments (Function<Order,Boolean>) …
Run Code Online (Sandbox Code Playgroud)

java lambda functional-programming java-8 functional-interface

6
推荐指数
1
解决办法
442
查看次数

在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 ????;
    }
Run Code Online (Sandbox Code Playgroud)

如果需要其他类:

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) …
Run Code Online (Sandbox Code Playgroud)

java functional-programming predicate java-8 functional-interface

3
推荐指数
2
解决办法
718
查看次数