🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators Bag
This page was created by Lars.olofsson on 2021-02-11. Last edited by Wikiadmin on 2026-07-29.

A Bag is an OCL collection for OCL expressions where you want to keep duplicate values; use it when each occurrence must remain available for iteration or later collection operations.

Create a Bag

Use Bag{ ... } to create a Bag literal. Separate elements with commas.

Bag{14, 22, 12, 53, 2, 11, 66}

A Bag is an unordered collection. Unlike a Set, it allows the same value to occur more than once.

Bag{1, 2, 2, 3}

In this example, 2 occurs twice. Use a Bag when those two occurrences must be retained.

Iterate over Bag elements

Use ->collect(...) to evaluate an expression for every element in the Bag. The name before | is the iterator variable: it represents the current element.

Bag{14, 22, 12, 53, 2, 11, 66}->collect(i | DoSomthingWithAnInt(i))

Here, i is each integer in turn. The expression calls DoSomthingWithAnInt(i) for every entry, including repeated entries.

You can create and iterate over a Bag of strings in the same way:

Bag{'String', 'EmailAddress'}->collect(s | DoSomthingWithAString(s))

In this example, s is each string in the Bag.

Choose Bag, Set, or Sequence

Collection Use it when Duplicate values Example
Bag Every occurrence matters. Kept. Bag{1, 2, 2}
Set You need each value only once. Removed. Set{1, 2, 2}
Sequence You need a defined sequence, such as a numeric range for iteration or numbering. See the Sequence operator behavior. Sequence{0..20}

For example, choose Bag{'Email', 'Email'} when both entries must be processed. Choose Set{'Email', 'Email'} when processing the value once is enough. For a fuller comparison, see Set vs bag.

Convert a value or collection to a Bag

Use asBag() when you need a Bag from an existing value or collection. It wraps a single object in a one-element Bag and preserves duplicates when they exist in the input collection.

Use Bags with collection operations

Bags can be used with collection operations. For example, union combines Bag contents and retains duplicate occurrences, while intersection returns Bag elements that are also present in the supplied Bag.

See also