scala-collection-contrib icon indicating copy to clipboard operation
scala-collection-contrib copied to clipboard

Add groupByOrdered functions

Open sake92 opened this issue 1 year ago • 0 comments
trafficstars

Motivation

When querying relational databases you usually get a flat result (unless using an ORM).
But on the API layer you usually want to expose that information as structured object (usually JSON).
The current groupBy methods do not maintain the original ordering, so you have to be careful not to destroy the ordering you get from an SQL query.

Implementation

Here is my current implementation: https://github.com/sake92/squery/blob/main/squery/src/ba/sake/squery/utils/seqUtils.scala
It's using a mutable.LinkedHashMap.
Not sure if it can be optimized, I'm not a perf expert.

There are 3 variations:

  • def groupByOrdered[K, V](extractKey: T => K): Map[K, Seq[T]] -> just groups the results by key, and puts them in a map
  • def groupByOrdered[K, V](extractKey: T => K, extractValue: T => V): Map[K, Seq[V]] -> same as above, but you can extract the result value too, sometimes you don't need everything that query returned
  • def groupByOrderedOpt[K, V](extractKey: T => K, extractValue: T => Option[V]): Map[K, Seq[V]] -> same as above, but it flattens the Options, very useful when you have a LEFT JOIN

sake92 avatar Aug 09 '24 15:08 sake92