Reputation: 18780
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?
Upvotes: 16
Views: 20957
Reputation: 26773
Do it like this:
CollectionUtils.emptyIfNull(collection).contains(x)
There is also an equivalent version for SetUtils
, MapUtils
, ListUtils
, etc.
This code is longer, so it seems to me it's mainly useful when you need a single expression for a Lambda.
Upvotes: 3
Reputation: 12766
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?
Upvotes: 11