Java stream – elegant way to do stream on nullable list

This has been troubling me for a while.
So I have a Product class that has a list of Image (the list could be null).
I want to do

product.getImages().stream().filter(...)

But as product.getImages() could be null, I can’t directly do above but have to wrap it with Optional.ofNullable(...).ifPresent(...)

Optional.ofNullable(product.getImages())
    .ifPresent(imgs->imgs.stream().filter(...))

To me it looks cumbersome even when compared to:

if(product.getImages() != null){
    product.getImages().stream().filter(...)
}

Assuming I can’t change Product::getImages (to make it not return null), is there a more elegant way?

Answer

There is Optional.stream, which gives you an empty stream if the optional is empty, otherwise it is a singleton stream of the element wrapped by the optional.

You can do something like:

Stream<Image> imageStream = 
    Optional.ofNullable(product.getImages())
        .stream()
        .flatMap(Collection::stream)
        .filter(...);

imageStream will be empty if getImages returns null.

There is also Stream.ofNullable (thanks to Holger for reminding me!), which can replace Optional.ofNullable(product.getImages()).stream()

Stream<Image> imageStream = 
    Stream.ofNullable(product.getImages())
        .flatMap(Collection::stream)
        .filter(...);