Removes all elements from the invoking collection except those in collection.
Collection Interface retainAll() Method:
Removes all elements from the invoking collection except those in collection. It returns true if the collection changed. Otherwise, returns false.
Syntax :
boolean retainAll(Collection collection);
Example :
import java.util.*;
public class CollectionInterfaceRetainAllMethod {
public static void main(String[] args){
Collection collection = new LinkedList();
ArrayList arraylist = new ArrayList();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
arraylist.add(1);
arraylist.add(2);
System.out.println("Before retainAll :" + collection);
collection.retainAll(arraylist);
System.out.println("After retainAll :" + arraylist);
System.out.println("After retainAll :" + collection);
}
}
Output :
|
Before retainAll :[1, 2, 3, 4]
After retainAll :[1, 2] After retainAll :[1, 2] |

[ 0 ] Comments