Reputation: 8229
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!
Upvotes: 4
Views: 169
Reputation: 15758
When testing(unit testing). Collections.singleton
is a one line way to turn your subject into a collection.
The alternative is two lines and not onerous.
Upvotes: 0
Reputation: 9635
From the API
remove(Object o)
Removes a single instance of the specified element from this collection, if it is present
and:
removeAll(Collection c)
Removes all of this collection's elements that are also contained in the specified collection
So, if your collection has more than one occurance of the element you wish to remove, you would have to execute collection.remove(element) several times, but removeAll only once. As removeAll takes a collection as argument, Collection.singleton can offer you a convenient way to create a collection with only one argument.
Upvotes: 3
Reputation: 13872
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.
Upvotes: 5
Reputation: 13890
The former removes all occurrences of the element within collection, the latter removes only first occurrence.
Upvotes: 8