Retriving unique set of elements from different Sets
What method can be used to return a set of elements that can be found only in set a or se开发者_高级运维t b, but not in both Sets ?
You're looking for the symmetric difference.
In theory, create a union of both sets and delete the intersection:
Set a = getSetA();
Set b = getSetB();
// create union
Set union = new Set(a);
union.addAll(b);
// remove intersection
for (Object inA : a)
if(b.contains(inA))
union.remove(inA);
Set<Integer> s1 = new HashSet<Integer>();
Set<Integer> s2 = new HashSet<Integer>();
s1.add(2);
s1.add(1);
s2.add(3);
s2.add(1);
removeAll :
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
System.out.println(s2.removeAll(s1)); // true
System.out.println(s2); // [3]
retainAll (intersection) :
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets
System.out.println(s2.retainAll(s1)); // true
System.out.println(s2); // [1]
addAll (union):
Adds all of the elements in the specified collection to this set if they're not already present (optional operation).
System.out.println(s1.addAll(s2)); //true
System.out.println(s1); //[1,2,3]
I think you need the difference. So for sets s1 and s2: s1.removeAll(s2)
精彩评论