You can use symmetricDifference in OCL to find the elements that occur in one collection but not in the other; it is useful when you need to identify mismatched members or check whether two collections contain the same members.
What symmetricDifference returns
collection1->symmetricDifference(collection2) returns the elements that belong to either input collection, excluding elements that occur in both.
In other words, it removes the shared elements and keeps the elements unique to each side.
| Collection 1 | Collection 2 | Result of Collection 1->symmetricDifference(Collection 2)
|
|---|---|---|
Set{0, 1, 3, 5, 6}
|
Set{0, 1, 3, 5, 7}
|
Set{6, 7}
|
Set{0, 1, 3, 5}
|
Set{0, 1, 3, 5}
|
An empty collection |
Set{0, 1, 3, 5}
|
Set{}
|
Set{0, 1, 3, 5}
|
Compare two collections
Use symmetricDifference when your question is: Which members do these collections not share?
For example, this expression returns an empty collection when ExpectedMembers and ActualMembers have no members that are exclusive to either collection:
ExpectedMembers->symmetricDifference(ActualMembers)You can test that result with length:
ExpectedMembers->symmetricDifference(ActualMembers)->length = 0This is a membership comparison. Use Set when you want a collection with no duplicates before performing this kind of comparison.
symmetricDifference compared with difference
Do not confuse symmetricDifference with difference.
| Operator | What it keeps | Example with A = Set{0, 1, 3, 5, 6} and B = Set{0, 1, 3, 5, 7}
|
|---|---|---|
A->difference(B)
|
Elements in A that are not in B
|
Set{6}
|
A->symmetricDifference(B)
|
Elements unique to A or unique to B
|
Set{6, 7}
|
Use intersection when you instead need the elements that both collections have in common.
Example
The following expression finds the numbers that differ between two sets. The values 0, 1, 3, and 5 occur in both sets, so they are removed. Only 6 and 7 remain.
Set{0, 1, 3, 5, 6}->symmetricDifference(Set{0, 1, 3, 5, 7})Watch the symmetricDifference walkthrough for a step-by-step demonstration.
