Scala GroupBy preserving insertion order?

后端 未结 4 1402
囚心锁ツ
囚心锁ツ 2020-12-29 21:06

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 (Link

4条回答
  •  情深已故
    2020-12-29 21:57

    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
    

提交回复
热议问题