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?
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list.
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
Collection contains() method in Java with ExamplesThis method returns a boolean value depicting the presence of the element. If the element is present, it returns true, else it returns false. Parameters: This method accepts a mandatory parameter element of type Object which is to be checked in this collection.
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?
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