×

Java Programs

Java Practice

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

Given a Vector collection, we have to remove all elements that do not contain in the specified collection.
Submitted by Nidhi, on May 25, 2022

Problem statement

In this program, we will create two Vector collections with different types of elements. Then we will remove all elements of the Vector collection that does not contain in the specified collection using the retainAll() method.

Source Code

The source code to remove all elements of the Vector collection that does not contain in the specified collection is given below. The given program is compiled and executed successfully.

// Java program to remove all elements of Vector collection does not 
// contain in the specified collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Vector vec1 = new Vector();
    Vector vec2 = new Vector();

    vec1.add(10);
    vec1.add(20.5);
    vec1.add(true);
    vec1.add("Hello World");

    vec2.add(10);
    vec2.add(true);

    System.out.println("Vector Vec1 : " + vec1);
    System.out.println("Vector Vec2 : " + vec2);

    vec1.retainAll(vec2);

    System.out.println("\nVector Vec1 : " + vec1);
    System.out.println("Vector Vec2 : " + vec2);
  }
}

Output

Vector Vec1 : [10, 20.5, true, Hello World]
Vector Vec2 : [10, true]

Vector Vec1 : [10, true]
Vector Vec2 : [10, true]

Explanation

In the above program, we imported the "java.util.*" package to use the Vector class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created 2 Vector collections vec1, vec2 with different types of elements. Then we used the retainAll() method and remove all elements in the Vector collection vec1 that does not contain in the specified collection vec2. After that, we printed the updated vector collections.

Java Vector Class Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.