Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does groupBy in Scala change the ordering of a list's items?

Tags:

People also ask

Does groupBy preserve order Scala?

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.

How does groupBy work in Scala?

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.

Does Scala set maintain 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.

Are lists ordered in Scala?

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?