Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of removing element from collection as set with one object

I found next code in official java docs:

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

I couldn't figure out advantages of this approach. Why not usual element removing?

collection.remove(element);

Thanks!

like image 553
bsiamionau Avatar asked Dec 05 '22 12:12

bsiamionau


2 Answers

The former removes all occurrences of the element within collection, the latter removes only first occurrence.

like image 164
Mikhail Vladimirov Avatar answered Dec 07 '22 00:12

Mikhail Vladimirov


Acc. to docs:

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

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

while collection.remove(element); removes a single instance of the specified element from this collection

So, to remove all instances, you've to use a loop construct with latter approach. while with first one it's just one line job.

like image 31
Azodious Avatar answered Dec 07 '22 02:12

Azodious