推 Argosde: order 1-n* orderDetail 1-1* product 10/15 22:36
→ Argosde: filter会变成 getOrderdetails().stream().anyMatch(...) 10/15 22:39
→ Argosde: 这样filter会筛选到orderDetails吗? 10/15 22:41
那是我看错了,不过道理还是一样,第一步是过滤出 Order,然后再对 Order
中的细节做过滤与处理(转为字串描述),第三步则是显示结果 …
这问题其实很有趣,也是重构 for 循环时不错的案例…
orders.stream()
.filter(order -> anyAmountGTFiveAndHasProduct(order)) // 符合的 Order
.map(order -> descOfAmountGTFiveAndHasProduct(order)) // 细节描述
.forEach(out::println); // 显示
public static boolean anyAmountGTFiveAndHasProduct(Order order) {
return order.getOrdertails().stream().anyMatch(
detail -> isAmountGTFiveAndHasProduct(detail));
}
public static String descOfAmountGTFiveAndHasProduct(Order order) {
return order.getOrdertails().stream()
.filter(detail -> isAmountGTFiveAndHasProduct(detail))
.map(detail -> String.format("%s Buy %s * %d", order.getId(), detail.getProduct().getName(), detail.getAmount()))
.collect(joining("%n"));
}
public static boolean isAmountGTFiveAndHasProduct(OrderDetail detail) {
return detail.getAmount() > 5 && detail.getProduct() != null;
}