Benefits of removing an item from a collection specified by a single object

I found the following code in official java docs :

collection.removeAll(Collections.singleton(element)); 

I could not understand the benefits of this approach. Why isnโ€™t the regular element deleted?

 collection.remove(element); 

Thanks!

+4
source share
4 answers

The former deletes all occurrences of an element in the collection; the latter deletes only the first occurrence.

+8
source

Acc. to the documents:

consider the following idiom to remove all instances of the specified element, e, from the collection, c

 collection.removeAll(Collections.singleton(element)); 

while collection.remove(element); removes one instance of the specified item from this collection

So, to remove all instances, you must use the loop construct with the latest approach. while with the first - this is just one task per line.

+5
source

From API

delete (object o)
Removes one instance of the specified item from this collection, if present.

and

removeAll (Collection c)
Deletes all items in the collection that are also contained in the specified collection.

So, if your collection has more than one instance of the element that you want to remove, you will need to execute collection.remove (element) several times, but removeAll only once. Since removeAll takes a collection as an argument, Collection.singleton can offer you a convenient way to create a collection with just one argument.

+3
source

When testing (unit testing). Collections.singleton is a one-line way to turn your object into a collection. The alternative is two lines, not burdensome.

0
source

All Articles