Wednesday, May 18, 2011

Bulk Operations on collections in java

The bulk operations perform some operation on an entire Collection in a single shot. They are shorthands in the sense that each of them can be simulated, perhaps less efficiently, using the operations described above.
  • containsAll: Returns true if the target Collection contains all of the elements in the specified Collection (c).
  • addAll: Adds all of the elements in the specified Collection to the target Collection.
  • removeAll: Removes from the target Collection all of its elements that are also contained in the specified Collection.
  • retainAll: Removes from the target Collection all of its elements that are not also contained in the specified Collection. That is to say, it retains only those elements in the target Collection that are also contained in the specified Collection.
  • clear: Removes all elements from the Collection.
The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation. As a simple example of the power of the bulk operations, consider following idiom to remove all instances of a specified element, e from a Collection, c.:
c.removeAll(Collections.singleton(e));
More specifically, suppose that you want to remove all of the null elements from a Collection:

c.removeAll(Collections.singleton(null));
This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element.

No comments:

Post a Comment

Chitika