null-safe Collection contains method

12,186

You should instead be applying the Null Object Pattern here and use an empty collection, rather than a null collection. Of course, perhaps this is appropriate for your problem, but without more context it's hard to tell. In other words, I think you are solving the wrong problem -- why might collection be null in the first place?

Share:
12,186
wrschneider
Author by

wrschneider

Updated on June 28, 2022

Comments

  • wrschneider
    wrschneider almost 2 years

    What's the best way to do null-safe contains on a Java collection?

    in other words -

     if (collection != null && collection.contains(x))
    

    ?

    I was hoping Apache commons-collections had something like CollectionUtils.contains(collection, x) that would simply return false if the collection was null, as there is with size(), which treats null like an empty collection.

    However, it seems like there is no such thing - did I just miss it?