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.
Scala groupBy is used for grouping of elements based on some criteria defined as a predicate inside the function. This function internally converts the collection into map object and this map object work on key value pair. This is basically used for storing and retrieving of the elements.
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.
In Scala we do not sort Lists in-place. They are immutable. But we use lambda expressions, and the Ordering type, to create sorted copies of these lists.
This code is from a Scala Worksheet:
case class E(a: Int, b: String) val l = List( E(1, "One"), E(1, "Another One"), E(2, "Two"), E(2, "Another Two"), E(3, "Three") ) l.groupBy(x => x.a) // res11: scala.collection.immutable.Map[Int,List[com.dci.ScratchPatch.E]] = // Map( // 2 -> List(E(2,Two), E(2,Another Two)), // 1 -> List(E(1,One), E(1,Another One)), // 3 -> List(E(3,Three)) // )
You will notice that groupBy returns a map, but that the ordering of the elements are now different to the way they were before. Any idea why this happens, and what the best way is to avoid this?
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