Dart MultiSet
last modified April 4, 2025
In Dart, MultiSet is a collection that allows duplicate elements while keeping track of their counts. It's also known as a bag or multiset data structure.
Unlike Set which stores unique elements, MultiSet maintains element counts. It's useful when you need to count occurrences or handle non-unique collections.
Creating a MultiSet
First, add the collections package to your pubspec.yaml. Then import it to use MultiSet.
import 'package:collection/collection.dart'; void main() { var fruitBag = MultiSet<String>(); fruitBag.add('apple'); fruitBag.add('banana'); fruitBag.add('apple'); print(fruitBag); print('Apple count: ${fruitBag.count('apple')}'); }
We create a MultiSet of fruits and add duplicates. The count method shows how many times 'apple' appears. MultiSet preserves insertion order by default.
$ dart main.dart MultiSet(apple, apple, banana) Apple count: 2
MultiSet from Iterable
You can create a MultiSet directly from an existing Iterable collection.
import 'package:collection/collection.dart'; void main() { var colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']; var colorBag = MultiSet.from(colors); print(colorBag); print('Blue count: ${colorBag.count('blue')}'); print('Distinct colors: ${colorBag.distinct()}'); }
This creates a MultiSet from a list with duplicates. The distinct method returns unique elements. Counts are maintained automatically during creation.
$ dart main.dart MultiSet(red, red, blue, blue, blue, green) Blue count: 3 Distinct colors: (red, blue, green)
Modifying MultiSet
MultiSet provides various methods to modify its contents and counts.
import 'package:collection/collection.dart'; void main() { var letters = MultiSet<String>(); // Add elements letters.add('a'); letters.addAll(['b', 'c', 'a', 'b']); // Remove elements letters.remove('b'); letters.removeAll('a'); // Add with count letters.add('d', count: 3); print(letters); print('Total elements: ${letters.size}'); }
We demonstrate adding and removing elements. The add method can take a count parameter. size returns the total count of all elements including duplicates.
$ dart main.dart MultiSet(c, b, d, d, d) Total elements: 5
MultiSet Operations
MultiSet supports mathematical operations like union, intersection, and difference.
import 'package:collection/collection.dart'; void main() { var set1 = MultiSet.from(['a', 'b', 'b', 'c']); var set2 = MultiSet.from(['b', 'c', 'c', 'd']); print('Union: ${set1.union(set2)}'); print('Intersection: ${set1.intersection(set2)}'); print('Difference: ${set1.difference(set2)}'); // Subset checks print('Contains all: ${set1.containsAll(set2)}'); print('Contains any: ${set1.containsAny(set2)}'); }
These operations work on element counts. Union takes maximum counts, intersection takes minimum counts, and difference subtracts counts. Contains methods check relationships between multisets.
$ dart main.dart Union: MultiSet(a, b, b, c, c, d) Intersection: MultiSet(b, c) Difference: MultiSet(a, b) Contains all: false Contains any: true
Counting and Statistics
MultiSet provides methods to analyze element counts and frequencies.
import 'package:collection/collection.dart'; void main() { var words = MultiSet.from([ 'apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'kiwi', 'banana' ]); print('Total words: ${words.size}'); print('Unique words: ${words.distinct().length}'); print('Most common: ${words.mostCommon()}'); print('Apple frequency: ${words.frequency('apple')}'); // Filter by count var commonWords = words.where((e) => words.count(e) > 1); print('Repeated words: $commonWords'); }
This shows various counting operations. mostCommon returns elements sorted by count. frequency is an alias for count. The where method filters elements.
$ dart main.dart Total words: 8 Unique words: 4 Most common: (apple: 3, banana: 3, orange: 1, kiwi: 1) Apple frequency: 3 Repeated words: (apple, apple, apple, banana, banana, banana)
Best Practices
- Element Equality: Ensure elements properly implement == and hashCode.
- Memory Usage: Be mindful of memory with large counts.
- Ordering: Don't rely on iteration order unless sorted.
- Counting: Use for frequency analysis and histogram use cases.
Source
This tutorial covered Dart's MultiSet with practical examples demonstrating its key features and usage patterns for counting collections.
Author
List all Dart tutorials.