Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala GroupBy preserving insertion order?

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.

like image 208
Vinicius Seufitele Avatar asked Mar 07 '12 01:03

Vinicius Seufitele


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.

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


1 Answers

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 
like image 54
Luigi Plinge Avatar answered Sep 20 '22 14:09

Luigi Plinge