Java Collection Tutorial - Java ArrayList .retainAll ( Collection <?> c)








Syntax

ArrayList.retainAll(Collection <?> c) has the following syntax.

public boolean retainAll(Collection <?> c)

Example

In the following code shows how to use ArrayList.retainAll(Collection <?> c) method.

/* w  w w . j a va 2 s  .  c o  m*/
import java.util.ArrayList;

public class Main {
  public static void main(String args[]) {
    ArrayList<Integer>  arrlist = new ArrayList<Integer> ();
  
    arrlist.add(1);
    arrlist.add(2);
    arrlist.add(3);
    arrlist.add(4);
    arrlist.add(5);

    ArrayList<Integer>  arrlist2 = new ArrayList<Integer> ();
    arrlist2.add(1);
    arrlist2.add(2);
    arrlist2.add(3);

    
    arrlist.retainAll(arrlist2); 

    System.out.println(arrlist);
    


  }
}

The code above generates the following result.