The groupBy method in Lists, Maps, etc., generate a Map after the function.
Is there a way to use the groupBy to generate a Map that preserves insertion order (LinkedHashMap, for instance)?
I'm using for loops to insert manually, but I wanted to know if one of the useful already-defined functions could help me.
Thanks in advance.
groupBy as defined on TraversableLike produces an immutable. Map , so you can't make this method produce something else. The order of the elements in each entry is already preserved, but not the order of the keys. The keys are the result of the function supplied, so they don't really have an order.
In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest element is at the head of the list. It maintains insertion order.
groupBy
as defined on TraversableLike
produces an immutable.Map
, so you can't make this method produce something else.
The order of the elements in each entry is already preserved, but not the order of the keys. The keys are the result of the function supplied, so they don't really have an order.
If you wanted to make an order based on the first occurrence of a particular key, here's a sketch of how you might do it. Say we want to group integers by their value / 2:
val m = List(4, 0, 5, 1, 2, 6, 3).zipWithIndex groupBy (_._1 / 2) val lhm = LinkedHashMap(m.toSeq sortBy (_._2.head._2): _*) lhm mapValues (_ map (_._1)) // Map(2 -> List(4, 5), 0 -> List(0, 1), 1 -> List(2, 3), 3 -> List(6)) // Note order of keys is same as first occurrence in original list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With