gpt4 book ai didi

java - 在 Java 8 中组合函数和谓词

转载 作者:搜寻专家 更新时间:2023-11-01 04:07:22 25 4
gpt4 key购买 nike

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

最佳答案

您不需要 Predicate。只需计算总和并检查它是否 > 1000。

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

或者,正如 Holger 评论的那样,Predicate 接口(interface)是一个更合适的函数式接口(interface),当您想要使用返回一个 boolean 的单个参数实现一个函数时:

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

关于java - 在 Java 8 中组合函数和谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com