🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators union
This page was created by Alexandra on 2017-08-14. Last edited by Wikiadmin on 2026-07-29.

You use union in OCL to combine the elements of one collection with those of another collection.

Syntax

selfCollection->union(otherCollection)

For a Bag (a collection that allows duplicate elements), the documented signature is:

union(bag : Bag(T)) : Bag(T)

T means the element type of the collection. The collection supplied as the argument must contain compatible elements.

What union returns

union returns a collection containing the elements from both the collection before -> and the collection passed as the argument.

Collection kind Result behavior
Bag Includes all elements from both Bags. Because a Bag permits duplicates, the same value can occur more than once in the result.
Set Combines the elements from both Sets. An element that occurs in both Sets occurs once in the result.

Examples

Combine Bags

In this example, both inputs are Bags. The value 'a' is present in each input, so it occurs twice in the result.

Bag{'a', 'b'}->union(Bag{'a', 'c'})
-- Result: Bag{'a', 'b', 'a', 'c'}

Use this form when repeated occurrences are meaningful in your expression.

Combine Sets

In this example, the two Sets share 0. The result contains 0 once.

Set{0, 1, 3, 5}->union(Set{0, 4, 6})
-- Result: Set{0, 1, 3, 5, 4, 6}

If 0 is removed from the second Set, it remains in the union because it is still present in the first Set. An element is absent from the union only when neither input contains it.

Combine collections of objects

Collections commonly contain model objects rather than literal values. For example, if self.AssignedPerson and self.Reviewer both contain the same Person object, a Set-based union includes that object once. This follows object identity: the same object is not treated as two different objects merely because it is reachable from both collections.

self.AssignedPerson->union(self.Reviewer)

When to use union

Use union when you need one collection that represents membership in either source collection. For example, use it to produce a recipient collection from people assigned to an item together with its reviewers.

Do not use union when you need only elements present in both collections; use the collection intersection operator instead. Do not use it when you need to remove elements found in another collection; use the difference operator instead.

You can inspect the operators available for a collection in the OCL Editor. See OCL General Operators. For a live walkthrough of collection operators, including union, watch the walkthrough.

See also