14

Is there any way so that the below can be performed as one set of stream operations, instead of explicitly checking if recommendedProducts is empty then return default list else return the filtered list?

public List<Product> getRecommendedProducts() {
    List<Product> recommendedProducts 
        = this.newProducts
              .stream()
              .filter(isAvailable)
              .collect(Collectors.toList());

    if (recommendedProducts.isEmpty()) {
        return DEFAULT_PRODUCTS;
    }

    return recommededProducts;
}
ETO
  • 6,970
  • 1
  • 20
  • 37
user3495691
  • 451
  • 1
  • 5
  • 16
  • 4
    What's wrong with your existing code? – Andy Turner Oct 07 '19 at 20:45
  • @AndyTurner Agree. The code is good as it is. The only improvement I would do is using *ternary operator* instead of *if-else* statement. It is still a matter of taste though. – ETO Oct 07 '19 at 20:53
  • @ETO There is nothing wrong, but I was trying/hoping to find out if there is a way to do it just by using Stream APIs with out explicit condition checks. Thanks for the reply - I like the ternary operator suggestion. – user3495691 Oct 07 '19 at 21:51

3 Answers3

9

You can try this:

List<Product> recommendedProducts 
        = this.newProducts
              .stream()
              .filter(isAvailable)
              .collect(Collectors.collectingAndThen(Collectors.toList(), list -> list.isEmpty() ? DEFAULT_PRODUCTS : list));
Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29
5

While you could achieve your goal using Optional, I would still opt for plain old ternary operator.

In this particular case it makes much more sense and improves readability:

return recommendedProducts.isEmpty() ? DEFAULT_PRODUCTS : recommendedProducts;
Naman
  • 27,789
  • 26
  • 218
  • 353
ETO
  • 6,970
  • 1
  • 20
  • 37
3

Yes by using Optional

return Optional.of(this.newProducts.stream()
                                   .filter(isAvailable)
                                   .collect(Collectors.toList()))
                    .filter(l->!l.isEmpty())
                    .orElse(DEFAULT_PRODUCTS);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98