What is a multimap, and what are the two ways to build one?
A map in which one key can have several values, like a dictionary word with several meanings. Either map each key to a collection of its values, or adapt the underlying structure to allow repeated keys.
German Schloss means both "castle" and "lock", so a German-English dictionary needs two entries under one key: (Schloss, castle) and (Schloss, lock). A plain map would let the second put overwrite the first. A multimap keeps both. (This is why "dictionary" is sometimes used as another name for a multimap. Careful: Python's dict and Java's old java.util.Dictionary are plain maps, not multimaps.)
Two ways to build one:
- Key โ collection of values. Use an ordinary map whose value is a list or set.
put(k, v)fetches the collection for k (creating it if needed) and adds v. This is what most code does: Javamap.computeIfAbsent(k, x -> new ArrayList<>()).add(v), Pythoncollections.defaultdict(list). - Adapt the structure. Let the underlying list, tree or hash table store several entries with the same key side by side, and make
getcollect all of them.
Option 1 groups each key's values together, so fetching them all costs one lookup. Java has no standard multimap class, so Map<K, List<V>> is the usual way; any map becomes a multimap like this.
A two-dimensional table (one row per key, one column per value) only works if every key has the same, fixed number of values, which is the exception.