2017-07-14 63 views
0

示例:過濾基於fromPrice和toPrice的價格的產品列表。他們既可以提供,也可以只提供一個。Java 8:基於可選條件的數據流和過濾器

  1. 查找其價格高於fromPrice
  2. 查找其價格低於toPrice
  3. 查找其價格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

不,可選項的目的不是取代空檢查。

但你的代碼可以通過避免重複,並避免返回空值(這顯然不是一個謂語有效值),如果兩個參數都爲空加以改進:

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

第一句就足以從我這裏賺一+1。 – Jubobs

+0

謝謝。這看起來不錯。但我在這裏得到一個編譯錯誤: 可選 price = product.getPrice(); 無法解析符號「產品」 –

+0

哦,是的,對不起,我的代碼沒有意義。讓我解決它。 –

0

您可以使用Apache的百科全書郎,它提供空安全比較:

ObjectUtils.compare(from, to) 

null is assumed to be less than a non-value