Write a Java program to remove all elements of Vector collection that do not contain in the specified collection


The code you provided is also written in Java and demonstrates the use of the retainAll() method to remove elements from a Vector that are not present in another Vector. Here's how the code works:

  • Two Vector objects, vec_list1 and vec_list2, are created to store string values.
  • The elements "Apple," "Banana," "Orange," "Cherry," and "Mango" are added to vec_list1 using the add() method.
  • The elements "Banana," "Grapes," "Cherry," and "Papaya" are added to vec_list2 using the add() method.
  • The initial contents of vec_list1 and vec_list2 are printed using System.out.println().
  • The retainAll() method is used on vec_list1 with vec_list2 as an argument. This method modifies vec_list1 to retain only the elements that are present in vec_list2.
  • The modified contents of vec_list1 and vec_list2 are printed using System.out.println().

Source Code

import java.util.*;
public class RemoveAll_Elements
{
	public static void main(String[] args)
	{
		Vector vec_list1 = new Vector();
		Vector vec_list2 = new Vector();
 
		vec_list1.add("Apple");
		vec_list1.add("Banana");
		vec_list1.add("Orange");
		vec_list1.add("Cherry");
		vec_list1.add("Mango");
 
		vec_list2.add("Banana");
		vec_list2.add("Grapes");
		vec_list2.add("Cherry");
		vec_list2.add("Papaya");
 
		System.out.println("Vector List 1 : " + vec_list1);
		System.out.println("Vector List 2 : " + vec_list2);
 
		vec_list1.retainAll(vec_list2);
 
		System.out.println("Vector List 1 : " + vec_list1);
		System.out.println("Vector List 2 : " + vec_list2);
	}
}

Output

Vector List 1 : [Apple, Banana, Orange, Cherry, Mango]
Vector List 2 : [Banana, Grapes, Cherry, Papaya]
Vector List 1 : [Banana, Cherry]
Vector List 2 : [Banana, Grapes, Cherry, Papaya]

Example Programs