Sunday 27 April 2014

TreeSet : retainAll :Retain the Elemets of a Collection

boolean retainAll(Collection<?> c)
Retains only the elements in this set that are contained in the specified collection (optional operation).Return true if this set changed as a result of the call.

import java.util.*;
class TreeSetRetainAll{
 public static void main(String args[]){
  TreeSet<Integer> mySet1 = new TreeSet<Integer> ();
  TreeSet<Integer> mySet2 = new TreeSet<Integer> ();
  TreeSet<Integer> mySet3 = new TreeSet<Integer> ();
  
  List<Integer> myList1 = new ArrayList<Integer> ();
  List<Integer> myList2 = new ArrayList<Integer> ();
  List<Integer> myList3 = new ArrayList<Integer> ();
  
  /*Adding Elements to the mySet1 */
  for(int i=0; i < 10; i++)
   mySet1.add(i);
   
  /* Copy data from mySet1 to mySet2 */
  mySet2.addAll(mySet1);
  mySet3.addAll(mySet1);
  myList3.addAll(mySet1);
  
  /* Add Elements to myList1 */
  for(int i=0; i < 20; i+=2)
   myList1.add(i);
   
  /* Add Elements to myList2 */
  for(int i=15; i< 25; i++)
   myList2.add(i);
   
  /* Display the Data */
  System.out.println("Data in mySet1 is \n" + mySet1); 
  System.out.println("\nData in mySet2 is \n" + mySet2);
  System.out.println("\nData in myList1 is \n" + myList1);
  System.out.println("\nData in myList2 is \n" + myList2);
  
  /* Retain the data of myList1 from mySet1 */
  System.out.println("\nIs mySet1 changed after retaining " + mySet1.retainAll(myList1));
  
  /* Retain the data of myList2 from mySet2 */
  System.out.println("\nIs mySet2 changed after retaining " + mySet2.retainAll(myList2));
  
  /* Retain the data of myList3 from mySet3 */
  System.out.println("\nIs mySet2 changed after retaining " + mySet3.retainAll(myList3));
  
  System.out.println("\nElements in mySet1 After retaining is \n" +mySet1);
  System.out.println("\nElements in mySet2 After retaining is \n" +mySet2);
  System.out.println("\nElements in mySet3 After retaining is \n" +mySet3);
   
 }
}

Output
Data in mySet1 is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Data in mySet2 is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Data in myList1 is
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Data in myList2 is
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

Is mySet1 changed after retaining true

Is mySet2 changed after retaining true

Is mySet2 changed after retaining false

Elements in mySet1 After retaining is
[0, 2, 4, 6, 8]

Elements in mySet2 After retaining is
[]

Elements in mySet3 After retaining is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment