title: Java 8: Stream and filter based on optional conditions
body: <p>Example: Filter a list of products that have a price based on fromPrice and toPrice. They could either both be supplied, or just one.</p>
  
  <ol>
  <li>Find all products whose price is greater than fromPrice</li>
  <li>Find all products whose price is less than toPrice</li>
  <li>Find all products whose price is between fromPrice and toPrice</li>
  </ol>
  
  <p>Product:</p>
  
  <pre><code>public class Product {
  
      private String id;
  
      private Optional&lt;BigDecimal&gt; price;
  
      public Product(String id, BigDecimal price) {
          this.id = id;
          this.price = Optional.ofNullable(price);
      }
  }
  </code></pre>
  
  <p>PricePredicate:</p>
  
  <pre><code>public class PricePredicate {
  
      public static Predicate&lt;? super Product&gt; isBetween(BigDecimal fromPrice, BigDecimal toPrice) {
          if (fromPrice != null &amp;&amp; toPrice != null) {
              return product -&gt; product.getPrice().isPresent() &amp;&amp; product.getPrice().get().compareTo(fromPrice) &gt;= 0 &amp;&amp;
                      product.getPrice().get().compareTo(toPrice) &lt;= 0;
          }
          if (fromPrice != null) {
              return product -&gt; product.getPrice().isPresent() &amp;&amp; product.getPrice().get().compareTo(fromPrice) &gt;= 0;
          }
          if (toPrice != null) {
              return product -&gt; product.getPrice().isPresent() &amp;&amp; product.getPrice().get().compareTo(toPrice) &lt;= 0;
          }
          return null;
      }
  }
  </code></pre>
  
  <p>Filters:</p>
  
  <pre><code>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());
  </code></pre>
  
  <p>Is there a way to improve my Predicate instead of having the if not null checks? Anything that can be done with optionals?</p>