fxe
fxe

Reputation: 575

Collection addAll removeAll returns boolean

C is a collection of type Set<T>, F(x) returns an collection of Set, what i want to do is to perform operations between sets like union, intersection, difference

// C union ( F(X) \ F(Y))
C.addAll( F(X).removeAll( F(Y)))); //error boolean because removeAll returns a boolean

alternative i could

C_aux = new HashSet<T> ( F(X));
C_aux.removeAll( F(Y)); 
C.addAll( C_aux);

anyway to do this without declaring the auxiliar collection ? (skip/ignore the boolean return)

Upvotes: 2

Views: 2506

Answers (2)

hoaz
hoaz

Reputation: 10153

java.util.Collection API:

a.retainAll(b); // intersection
a.removeAll(b); // difference
a.addAll(b); // union

Google Guava com.google.common.collect.Sets API:

Sets.union(a, b);
Sets.intersection(a, b);
Sets.difference(a, b);

You can write one-liner if that is what you actually need:

Sets.union(C, Sets.difference(F(X), F(Y)))

But remember that result set is read-only, so if you need real Set use C.removeAll instead

Upvotes: 6

brimborium
brimborium

Reputation: 9512

How about

C.addAll(A.removeAll(B)?A:A);

Normally I would consider this a joke, but in this case you could save creating a list. It is still as ugly as my "decorative" plant after I forgot to water it for about 3 months... :P

Edit: This of course also works, but still changes A.

A.removeAll(B);
C.addAll(A);

By the way: If A and B can not be changed in the method, I think there is no way around creating a temporary list (no matter whether you safe it in a variable or not). At least if C can initially contain elements.

Upvotes: 2

Related Questions