union method

MultiSet<T> union(
  1. MultiSet<T> other
)

Returns the union of this multiset with other.

The multiplicity of each element in the result is the maximum of its multiplicities in this multiset and other.

Example:

final p = MultiSet<String>.fromIterable(['a', 'a', 'a', 'c']);
final q = MultiSet<String>.fromIterable(['a', 'a', 'b', 'c', 'c']);
final result = p.union(q);
// result = {'a': 3, 'b': 1, 'c': 2}

Implementation

MultiSet<T> union(MultiSet<T> other) {
  final result = MultiSet<T>();
  final allElements = {..._elements.keys, ...other._elements.keys};

  for (var element in allElements) {
    final count = _max(
      _elements[element] ?? 0,
      other._elements[element] ?? 0,
    );
    if (count > 0) result.add(element, count);
  }

  return result;
}