ADVERTISEMENT
ADVERTISEMENT

# 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 Solution:

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.

Program/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.

ADVERTISEMENT
ADVERTISEMENT

Preparation

What's New

ADVERTISEMENT

Top Interview Coding Problems/Challenges!

ADVERTISEMENT

ADVERTISEMENT

Comments and Discussions!

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.