user3495691
user3495691

Reputation: 481

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

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

Upvotes: 15

Views: 5474

Answers (3)

ETO
ETO

Reputation: 7299

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;

Upvotes: 5

goedi
goedi

Reputation: 2123

You can try this:

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

Upvotes: 11

Ryuzaki L
Ryuzaki L

Reputation: 40088

Yes by using Optional

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

Upvotes: 3

Related Questions