Tuesday, 1 April 2014

containsAll : Search for a Collection of elements

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

import java.util.*;
class ListContainsAll{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  List<Integer> myList1 = new ArrayList<> ();
  List<Integer> myList2 = new ArrayList<> ();
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }
  
  /* Add Elements to myList1 */
  for(int i=5; i < 10; i++){
   myList1.add(i);
  }
  
  /* Add Elements to myList2 */
  for(int i=5; i < 12; i++){
   myList2.add(i);
  }
 
  
  System.out.println("Elements in the myList are");
  System.out.println(myList+"\n");
  
  System.out.println("Elements in the myList1 are");
  System.out.println(myList1+"\n");
  
  System.out.println("Elements in the myList2 are");
  System.out.println(myList2+"\n");
  
  System.out.print("Is myList contains all the elements of myList1 ");
  System.out.println(myList.containsAll(myList1));
  
  System.out.print("Is myList contains all the elements of myList2 ");
  System.out.println(myList.containsAll(myList2));
 }
}

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

Elements in the myList1 are
[5, 6, 7, 8, 9]

Elements in the myList2 are
[5, 6, 7, 8, 9, 10, 11]

Is myList contains all the elements of myList1 true
Is myList contains all the elements of myList2 false

1. throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this list

2. throws NullPointerException if the specified collection contains one
or more null elements and this list does not permit null elements



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment