Search code examples
scalacollectionsseq

Does scala.collection.Seq.groupBy() function preserve the order?


I'm trying to figure out:

  1. If scala.collection.Seq.groupBy() preservers the order. Meaning if I have List((true, 2), (true, 8)), and do groupBy by the first element which is the boolean, will I always end up with a list for true which has 2 before 8.

  2. Same question for toMap. Meaning if I do a toMap on the mentioned list, will I always end up having 8 for the key true, cause 8 comes after 2 and overrides it?

I could not find anything about the implementation in the scala doc: scala doc. I'm trying to decide whether write my own version of it to make sure the order is preserved.

Thanks!


Solution

  • The behavior is documented:

    A map from keys to traversable collections such that the following invariant holds: (xs groupBy f)(k) = xs filter (x => f(x) == k)

    means it's defined in terms of equals.

    Filter specifies "The order of the elements is preserved."

    Therefore, yes, ordering is preserved as specified.

    Similarly, toMap says:

    Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

    That is, last key in ordered collection provides the value.