Returning default list if the list is empty using java 8 Streams?

Viewed 2222

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;
}
3 Answers

You can try this:

List<Product> recommendedProducts 
        = this.newProducts
              .stream()
              .filter(isAvailable)
              .collect(Collectors.collectingAndThen(Collectors.toList(), list -> list.isEmpty() ? DEFAULT_PRODUCTS : list));

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;

Yes by using Optional

return Optional.of(this.newProducts.stream()
                                   .filter(isAvailable)
                                   .collect(Collectors.toList()))
                    .filter(l->!l.isEmpty())
                    .orElse(DEFAULT_PRODUCTS);
Related