Friday, 18 April 2014

HashSet : containsAll : Search for a Collection of Elements

public boolean containsAll(Collection<?> c)
Returns true if this set contains all of the elements of the specified collection.  

import java.util.*;
class HashSetContainsAll{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<> ();
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to the Set */
  for(int i=0; i < 20; i++)
   mySet.add(i);
   
  /* Add Elements to the List */
  for(int i=10; i<15; i++)
   myList.add(i);
  
  System.out.println("Elements in the Set are");
  System.out.println(mySet);

  System.out.println("\nElements in the list are");
  System.out.println(myList); 

  /* Search whether the mySet contains all the Elements of the myList */
  if(mySet.containsAll(myList)){
   System.out.println("Set contains all the Elements of the list");
  }
  else{
   System.out.println("Set doesn't contain all the Elements of the list");
  }
  
  /* Add 100 to the myList */
  myList.add(100);
  System.out.println("\nElements in the list are");
  System.out.println(myList); 
  
  /* Search whether the mySet contains all the Elements of the myList */
  if(mySet.containsAll(myList)){
   System.out.println("Set contains all the Elements of the list");
  }
  else{
   System.out.println("Set doesn't contain all the Elements of the list");
  }  
 }
}

Output
Elements in the Set are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18]

Elements in the list are
[10, 11, 12, 13, 14]
Set contains all the Elements of the list

Elements in the list are
[10, 11, 12, 13, 14, 100]
Set doesn't contain all the Elements of the list



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment