Java 8 Java8:基于可选条件的流和过滤器
示例:筛选价格基于fromPrice和toPrice的产品列表。它们可以同时提供,也可以只提供一个Java 8 Java8:基于可选条件的流和过滤器,java-8,java-stream,optional,Java 8,Java Stream,Optional,示例:筛选价格基于fromPrice和toPrice的产品列表。它们可以同时提供,也可以只提供一个 查找价格高于fromPrice的所有产品 查找所有价格低于toPrice的产品 查找价格介于fromPrice和toPrice之间的所有产品 产品: public class Product { private String id; private Optional<BigDecimal> price; public Product(String id,
public class Product {
private String id;
private Optional<BigDecimal> price;
public Product(String id, BigDecimal price) {
this.id = id;
this.price = Optional.ofNullable(price);
}
}
有没有办法改进我的谓词而不是进行if-notnull检查?使用optionals可以完成的任何操作?否,Optional的设计目的不是取代空检查 但是可以通过避免重复和避免在两个参数都为null时返回null(这显然不是谓词的有效值)来改进代码:
public static Predicate<Product> isBetween(BigDecimal fromPrice, BigDecimal toPrice) {
Predicate<Product> result = product -> true;
if (fromPrice != null) {
result = result.and(product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0);
}
if (toPrice != null) {
result = result.and(product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(toPrice) <= 0);
}
return result;
}
公共静态谓词isBetween(BigDecimal fromPrice,BigDecimal toPrice){
谓词结果=产品->真;
if(fromPrice!=null){
result=result.and(product->product.getPrice().isPresent()&&product.getPrice().get().compareTo(fromPrice)>=0);
}
if(toPrice!=null){
result=result.and(product->product.getPrice().isPresent()&&product.getPrice().get().compareTo(toPrice)否,可选选项不用于替换空检查
但是可以通过避免重复和避免在两个参数都为null时返回null(这显然不是谓词的有效值)来改进代码:
public static Predicate<Product> isBetween(BigDecimal fromPrice, BigDecimal toPrice) {
Predicate<Product> result = product -> true;
if (fromPrice != null) {
result = result.and(product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0);
}
if (toPrice != null) {
result = result.and(product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(toPrice) <= 0);
}
return result;
}
公共静态谓词isBetween(BigDecimal fromPrice,BigDecimal toPrice){
谓词结果=产品->真;
if(fromPrice!=null){
result=result.and(product->product.getPrice().isPresent()&&product.getPrice().get().compareTo(fromPrice)>=0);
}
if(toPrice!=null){
result=result.and(product->product.getPrice().isPresent()&&product.getPrice().get().compareTo(toPrice)您可以使用Apache Commons Lang,它提供空安全比较:
ObjectUtils.compare(from, to)
假定null小于非值
您可以使用Apache Commons Lang,它提供空安全比较:
ObjectUtils.compare(from, to)
null被假定为小于一个非值
第一句话足以从我这里获得+1。谢谢。这看起来不错。但我在这里得到一个编译错误:可选价格=产品。getPrice()哦,是的,对不起,我的代码没有意义。让我来修复它。谢谢。这正是我所做的。我会考虑价格是否应该始终是强制性的(无论如何,从代码到代码<空/代码>是一个拐角的情况)。。因此,您可以将product->true
替换为product->product.getPrice().isPresent()
,并从其他谓词中删除product.getPrice().isPresent()&&
。第一句话足以从我这里获得+1。谢谢。这看起来不错。但我在这里遇到了一个编译错误:Optional price=product.getPrice()哦,是的,对不起,我的代码没有意义。让我来修复它。谢谢。这正是我所做的。我会考虑价格是否应该始终是强制性的(无论如何,从代码到代码<空/代码>是一个拐角的情况)。。因此,您可以将product->true
替换为product->product.getPrice().isPresent()
,并从其他谓词中删除product.getPrice().isPresent()&&
。