Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null-safe Collection contains method

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?

like image 998
wrschneider Avatar asked Dec 12 '12 16:12

wrschneider


People also ask

How do you know if a collection is not null?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list.

How do you check if a collection contains a string in Java?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How contains method works internally in Java?

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.


1 Answers

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?

like image 186
Thorn G Avatar answered Nov 13 '22 13:11

Thorn G