Java Vector - retainAll() Method
The java.util.Vector.retainAll() method is used to retain only the elements in the given vector that are contained in the specified collection. In other words, it removes from the vector all of its elements that are not contained in the specified collection.
Syntax
public boolean retainAll(Collection<?> c)
Parameters
c |
Specify a collection of elements to be retained in the vector (all other elements are removed). |
Return Value
Returns true if the vector changed as a result of the call.
Exception
Throws NullPointerException, if the specified collection is null.
Example:
In the example below, the java.util.Vector.retainAll() method is used to retain only the elements in the given vector that are contained in the specified collection.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<Integer> vec1 = new Vector<Integer>(); Vector<Integer> vec2 = new Vector<Integer>(); //populating vec1 vec1.add(10); vec1.add(20); vec1.add(30); vec1.add(40); vec1.add(50); //populating vec2 vec2.add(20); vec2.add(40); vec2.add(60); //printing vec1 System.out.println("Before retainAll, vec1 contains: " + vec1); //apply retainAll method on vec1 vec1.retainAll(vec2); //printing vec1 System.out.println("After retainAll, vec1 contains: " + vec1); } }
The output of the above code will be:
Before retainAll, vec1 contains: [10, 20, 30, 40, 50] After retainAll, vec1 contains: [20, 40]
❮ Java.util - Vector