示例:过滤基于fromPrice和toPrice的价格的产品列表。他们既可以提供,也可以只提供一个。Java 8:基于可选条件的数据流和过滤器
- 查找其价格高于fromPrice
- 查找其价格低于toPrice
- 查找其价格fromPrice和toPrice
产品之间的所有产品所有产品所有产品:
public class Product {
private String id;
private Optional<BigDecimal> price;
public Product(String id, BigDecimal price) {
this.id = id;
this.price = Optional.ofNullable(price);
}
}
PricePredicate:
个public class PricePredicate {
public static Predicate<? super Product> isBetween(BigDecimal fromPrice, BigDecimal toPrice) {
if (fromPrice != null && toPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0 &&
product.getPrice().get().compareTo(toPrice) <= 0;
}
if (fromPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0;
}
if (toPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(toPrice) <= 0;
}
return null;
}
}
过滤器:
return this.products.stream().filter(PricePredicate.isBetween(fromPrice, null)).collect(Collectors.toList());
return this.products.stream().filter(PricePredicate.isBetween(null, toPrice)).collect(Collectors.toList());
return this.products.stream().filter(PricePredicate.isBetween(fromPrice, toPrice)).collect(Collectors.toList());
有没有改善我的谓词的方式,而不是如果不为null检查具有?任何可以用可选项来完成的事情?
第一句就足以从我这里赚一+1。 – Jubobs
谢谢。这看起来不错。但我在这里得到一个编译错误: 可选 price = product.getPrice(); 无法解析符号“产品” –
哦,是的,对不起,我的代码没有意义。让我解决它。 –