Friday 18 April 2014

HashSet : removeAll : Remove Collection Of elements

public boolean removeAll(Collection<?> c)
Removes from this set all of its elements that are contained in the specified collection. Return true if this set changed as a result of the call.

import java.util.*;
import java.util.*;
class HashSetRemoveAll{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<> ();
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  
  /* Add Elements to myList */
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("\nElements in mySet are ");
  System.out.println(mySet);
  
  System.out.println("\nElements in myList are ");
  System.out.println(myList);
  
  mySet.removeAll(myList);
  
  System.out.println("\nElements after calling removeAll is ");
  System.out.println(mySet);
 }
}

Output
Elements in mySet are
[20, 10, 30]

Elements in myList are
[20, 30, 40]

Elements after calling removeAll is
[10]



1. throws UnsupportedOperationException if the removeAll operation is not supported by this set
import java.util.*;
class HashSetRemoveAllUnsupported{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<> ();
  Set<Integer> unmodifiable;
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  
  /* Create a unmodifiable Set*/
  unmodifiable = Collections.unmodifiableSet(mySet);
  
  /* Add Elements to myList */
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("\nElements in mySet are ");
  System.out.println(mySet);
  
  System.out.println("\nElements in myList are ");
  System.out.println(myList);
  
  /*Trying to perform removeAll on unmodifiable Set */
  unmodifiable.removeAll(myList);
  
  System.out.println("\nElements after calling removeAll is ");
  System.out.println(unmodifiable);
 }
}

Output
Elements in mySet are
[20, 10, 30]

Elements in myList are
[20, 30, 40]
Exception in thread "main" java.lang.UnsupportedOperationException
      at java.util.Collections$UnmodifiableCollection.removeAll(Collections.java:1088)
      at HashSetRemoveAllUnsupported.main(HashSetRemoveAllUnsupported.java:28)






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment