Returning default list if the list is empty using java 8 Streams?
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;