Reputation: 481
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
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
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
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