user1814879
user1814879

Reputation: 984

Remove element vector java

I have 2 vectors with elements like :

vect 1 = [111111 5, 111111 5, 222222 5, 333333 5, 111111 2]
vect 2 = [111111 5, 222222 4, 333333 2, 111111 2, 444444 8, 333333 5, 111111 1, 222222 5]

How can I do in Java to remove elements of the vector 1 present in the vect 2 ?

I want get this result :

vect 2 = [222222 4, 333333 2, 444444 8, 111111 1]

Thank

Upvotes: 1

Views: 806

Answers (3)

Rajesh
Rajesh

Reputation: 384

Try removeAll method of Vector,

public static void main(String[] args) {
    Vector v1 = new Vector();
    Vector v2 = new Vector();

    v1.add(1111);
    v2.add(1111);
    v2.add(2222);

    v2.removeAll(v1);
    System.out.println(v2);

}

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can use the method removeAll(Collection<?> c) of Collection. This is applicable to any Collection.

So you can do the following:

List v1 = ....
List v2 = ....
v2.removeAll(v1); // Now v2 contains only elements of original v2 not present in v1

Upvotes: 5

Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 437

Use collToRemoveFrom.removeAll(collection);

Upvotes: 1

Related Questions