Scala how to group a map and then subgroup and transform values

I have an object like this:

case class MyObject(x : Int,y : String,...) {
   val buckets = 3
   def bucket = x % buckets // returns a number between 0 and |buckets|

(x is an arbitrary number)

for example assume "buckets = 3" and we have many objects

MyObject(x = 0, y = "Something", ...)
MyObject(x = 1, y = "Something else", ...)

Using "groupBy" I collect "MYObjects" using the x % buckets, so it will be like:

val objects : Seq[MyObject] = ...
val groupedObjects : Map[Int: Seq[MyObjects]] = objects.groupBy(obj => x.bucket)

now I want to transform each value and also regroup to sublists of the different type

so lets say for each item in group = 1 , I want to nest under an additional layer and store a different calculated value:

so lets say if bucket 0 after the initial grouping looked like:

bucket[0] = [obj1,obj2,...,objn]

I want to be able to transform bucket "0" to contain another nested grouping:

bucket[0] = Map(sub_bucket_0 -> [transformed(objects)...], sub_bucket_1 -> [transformed(object)...),....]

meaning that eventually I have a data structure with the type:


1 answer

  • answered 2018-01-11 20:56 jwvh

    I think what you're looking for is mapValues() which will modify the Map's value elements to new values and/or types.

    groupedObjects.mapValues(_.groupBy(/*returns new key type/value*/))
                  .mapValues(_.mapValues(*transform MyObject elements*/)))