Daniel Oliveira
Daniel Oliveira

Reputation: 1290

Java - Intercept two collections and get the remaining elements

I have two collections of Strings in java:

A: ("abc", "bcd" "cde")
B: ("abc", "cde")

I pretend to get a new collection that contains all elements that are in A and are not in B, in math something like: C = A\B

In this case C would be something like:

C: ("bcd")

How could this be done efficiently in java using collections?

Thanks.

Upvotes: 0

Views: 210

Answers (1)

blr
blr

Reputation: 968

You can use Collection's removeAll

// before a contained ["abc", "bcd" "cde"]
a.removeAll(b)
// now a contains ["abc", "bcd" "cde"]

if you do not want a to change, I'd recommend doing a deep copy of a into a new variable first c

Upvotes: 1

Related Questions