How do set, multiset, map and multimap differ?
Set: unique elements. Multiset: elements may repeat. Map: unique keys, one value each. Multimap: a key may carry several values.
* Dropping the values turns a map into a set; allowing repeats turns each into its "multi" version. *
| Stores | Duplicates | Example | |
|---|---|---|---|
| Set | elements | no | {a, b, c} |
| Multiset (bag) | elements | yes | {a, b, b, c, f, f} |
| Map | key → value | no duplicate keys | 4001 → Basel |
| Multimap | key → values | a key may repeat | "lock" → {padlock, door lock} |
Two ideas generate the whole family. A set is a map without values: its elements play the role of map keys, so the same implementation (a hash table or a search tree) serves both. "Multi" lifts the no-duplicates rule: a multiset may hold the same element several times, a multimap the same key with several values.
The names are not used consistently across languages and books, so when meeting a new collection type, ask the two questions directly: does it store values with the keys, and does it allow duplicates?
In libraries: Java's HashSet is literally backed by a HashMap with a dummy value. Python's collections.Counter is a multiset (element → count).
Where a multimap earns its place: whenever one key naturally has several values, a one-to-many relation.
- Inverted index (the core of a search engine): word → every document that contains it.
- Graph adjacency list: node → all its neighbours.
- Grouping: course → enrolled students, author → books, the result of a SQL
GROUP BY. - Web requests: a URL query string like
?tag=a&tag=brepeats a key, and so do HTTP headers such asSet-Cookie; Python'surllib.parse.parse_qsreturns key → list of values for exactly this reason.
Go deeper:
Multiset — multiplicity, and how a bag differs from a set.