Saturday 28 May 2011

Collection Operations on Lists–Simple and Bulk

Create the lists
List list1 = new ArrayList(); 
List list2 = new ArrayList();


Add the elements


// Add elements to the lists ...
list1.add("Hanuman");

Bulk Add
Copy all the elements from list2 to list1 (list1 += list2). list1 becomes the union of list1 and list2

list1.addAll(list2); 

Bulk Remove
Remove all the elements in list1 from list2 (list1 -= list2). list1 becomes the asymmetric difference of list1 and list2

list1.removeAll(list2); 

Intersection of Lists
Get the intersection of list1 and list2. list1 becomes the intersection of list1 and list2

list1.retainAll(list2); 

Remove all elements from a list

list1.clear(); 


Truncate the list


int newSize = 2;
list1.subList(newSize, list1.size()).clear();

No comments:

Post a Comment