Write a Java program to remove elements from Vector collection based on a specified predicate


The code is written in Java and demonstrates the usage of the Vector class to remove elements from a vector based on a specific condition using the removeIf method. Let's go through the code step by step:

  • The code starts with the import statement, which includes the required packages for the code to run successfully.
  • The class "RemoveElement" is defined, which serves as the main class for our program.
  • Inside the main method, a Vector object called "vec_list" is created using the Vector class. The Vector is parameterized with the Integer type.
  • Several integers are added to the vector using the add method. The integers range from 10 to 100 with increments of 10.
  • The line System.out.println("Vector Elements : " + vec_list); prints the elements of the vector to the console, displaying all the integers added to the vector.
  • The line vec_list.removeIf(val -> (val >= 70)); uses the removeIf method of the Vector class to remove elements from the vector based on the provided condition. In this case, it removes all elements greater than or equal to 70 from the vector. The condition is specified using a lambda expression (val -> (val >= 70)), which checks if the value of each element is greater than or equal to 70.
  • Finally, the line System.out.println("Vector Elements : " + vec_list); is executed again to print the updated elements of the vector to the console. After removing elements greater than or equal to 70, the vector now contains 10, 20, 30, 40, 50, and 60.

Source Code

import java.util.*;
public class RemoveElement
{
	public static void main(String[] args)
	{
		Vector < Integer > vec_list = new Vector < Integer > ();
		vec_list.add(10);
		vec_list.add(20);
		vec_list.add(30);
		vec_list.add(40);
		vec_list.add(50);
		vec_list.add(60);
		vec_list.add(70);
		vec_list.add(80);
		vec_list.add(90);
		vec_list.add(100);
 
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.removeIf(val -> (val >=70));
 
		System.out.println("Vector Elements : " + vec_list);
	}
}

Output

Vector Elements : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Vector Elements : [10, 20, 30, 40, 50, 60]

Example Programs