ACMNexus / google-collections

Automatically exported from code.google.com/p/google-collections
Apache License 2.0
0 stars 0 forks source link

Sets.complementOf( Set<A>, Set<A> ) to return AUB - A intersect B #162

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Not a defect, but an ehancement request:

I would like to see the Sets class have a method for returning: A UNION B
MINUS A INTERSECT B.

This is doable with two calls to Sets and a temp structure;
Set<A> union = Sets.union( a, b );
union.removeAll( Sets.intersect( a, b ) );

The problem with this approach is the memory overhead of creating the Union
struct.

Original issue reported on code.google.com by harschw...@gmail.com on 7 May 2009 at 6:10

GoogleCodeExporter commented 8 years ago
You can do this with Sets.union(Sets.difference(a, b), Sets.difference(b, a)).

Note that this is a read-only, *live* view, which you may not have realized 
(based on
your example code), so you might want to add .immutableCopy() to the end. Or you
could do it this way:

Set<A> xor = Sets.newHashSet();
xor.addAll(Sets.difference(a, b));
xor.addAll(Sets.difference(b, a));

I strongly suspect the need for this is too rare to justify a new method in the 
library.

Original comment by kevin...@gmail.com on 7 May 2009 at 6:24

GoogleCodeExporter commented 8 years ago
(btw, the reason these approaches are preferable to the code you suggest is 
that,
when the two sets have a large intersection, your code ends up producing an
overly-large, sparsely-populated hash set.)

Original comment by kevin...@gmail.com on 7 May 2009 at 6:25

GoogleCodeExporter commented 8 years ago

Original comment by kevin...@gmail.com on 11 May 2009 at 5:08