Scala mutable MultiMap addBinding and preserving insertion order

It looks like the MultiMap addBinding does not preserve the insertion order of values ​​bound to the same key, since the mechanism it uses is a HashSet. What could be an idiomatic way to preserve insertion order with MultiMap?


source to share

2 answers

Based on MultiMap

where it says:

/** Creates a new set.
*  Classes that use this trait as a mixin can override this method
*  to have the desired implementation of sets assigned to new keys.
*  By default this is `HashSet`.
*  @return An empty set of values of type `B`.
protected def makeSet: Set[B] = new HashSet[B]


You can simply define:

trait OrderedMultimap[A, B] extends MultiMap[A, B] {
    override def makeSet: Set[B] = new LinkedHashSet[B]




One way is probably to revert to a regular Map (not a MultiMap) using a collection for the value type, whereas that collection would be a collection type where order can be applied (i.e. not a set). As far as I understand, in order to preserve the broader insertion order that allows the element to be repeated, the natural Scala collection to use would be a Seq implementation (e.g. Vector or Queue, depending on the access patterns)



All Articles