Null-safe collection contains a method

What is the best way to make null-safe contains in a Java collection?

In other words -

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

?

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

However, there seems to be no such thing - did I just skip it?

+7
source share
1 answer

Instead, you should use the Null Object Pattern and use an empty collection, not an empty collection. Of course, perhaps this is suitable for your problem, but without much context it is hard to say. In other words, I think you are solving the wrong problem - why can a collection be null in the first place?

+10
source

All Articles