Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 309
user3495691 Avatar asked Oct 07 '19 20:10

user3495691


People also ask

What happens if you Stream an empty List Java?

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.

Does collectors toList return empty List?

Collector. toList() will return an empty List for you.

Does Java 8 support streams?

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.


1 Answers

You can try this:

List<Product> recommendedProducts 
        = this.newProducts
              .stream()
              .filter(isAvailable)
              .collect(Collectors.collectingAndThen(Collectors.toList(), list -> list.isEmpty() ? DEFAULT_PRODUCTS : list));
like image 190
Diego Marin Santos Avatar answered Oct 08 '22 17:10

Diego Marin Santos