在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;
}
}
Function<Order, Boolean>
?相比于返回boolean
并将方法放在Order
类中,有什么优势呢? - Kayamanif (products == null) { products = new ArrayList<>(); }
语句已经过时了,因为你总是用ArrayList
初始化products
字段。如果你想确保没有人会将其覆盖为null
,请将其声明为final
。 - Holgera -> { long value = 0; for(Product p: a.getProducts()) { value += p.getPrice(); if(value>1000) return true; } return false; }
不是很适合使用 stream,但是更有效率,因为它在超过阈值时可以立即返回,而不必继续处理所有元素。 - Holger