Tuesday 27 May 2014

LinkedList : retainAll : Retain Elements

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

import java.util.*;
class LinkedListRetainAll{
 public static void main(String args[]){
  LinkedList<Integer> myList = new LinkedList<> ();
  Set<Integer> mySet1 =new HashSet<> ();
  Set<Integer> mySet2 =new HashSet<> ();
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }
  
  /* Add Elements to mySet1 */
  for(int i=5; i < 15; i++){
   mySet1.add(i);
  }
  
  /* Add Elements to mySet2 */
  for(int i=10; i < 15; i++){
   mySet2.add(i);
  }
  
  System.out.println("Elements in myList are ");
  System.out.println(myList +"\n");
  System.out.println("Elements in mySet1 are ");
  System.out.println(mySet1 +"\n");
  System.out.println("Elements in mySet2 are ");
  System.out.println(mySet2 +"\n");
  
  myList.retainAll(mySet1);
  System.out.println("After retaining mySet1 from myList");
  System.out.println(myList +"\n");
  
  myList.retainAll(mySet2);
  System.out.println("After retaining mySet2 from myList");
  System.out.println(myList +"\n");
  
 }
}

Output
Elements in myList are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Elements in mySet1 are
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Elements in mySet2 are
[10, 11, 12, 13, 14]

After retaining mySet1 from myList
[5, 6, 7, 8, 9]

After retaining mySet2 from myList
[]


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment