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;
}
If the Stream is empty (and it doesn't matter if it's empty due to the source of the stream being empty, or due to all the elements of the stream being filtered out prior to the terminal operation), the output List will be empty too. Show activity on this post. You will get a empty collection.
Collector. toList() will return an empty List for you.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
You can try this:
List<Product> recommendedProducts
= this.newProducts
.stream()
.filter(isAvailable)
.collect(Collectors.collectingAndThen(Collectors.toList(), list -> list.isEmpty() ? DEFAULT_PRODUCTS : list));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With