Flatten a list of Anorm tuples

2019-08-08 21:44发布

Given a scala list such as:

List( ~(OuterObj,InnerObj1), ~(OuterObj, InnerObj2), ...) 

Where all the OuterObj's are the same and the InnerObj's can be different, I need to "group" this into a single OuterObj object that contains a list of the InnerObj's.

In other words, OuterObj has an attribute innerList that is empty, but I need to transform the original list into a single OuterObj such that:

OuterObj.innerList = List(InnerObj1, InnerObj2, ....)

I tried using .groupBy(_._1) but this didn't group the objects properly and I wasn't sure where to go from there.

In case context helps, the original List is a result of an Anorm join query with a one-to-many (1 outerObj to many innerObj) using the following parser pattern:

SQL(" joining outer on inner sql using a left join.. ").as(OuterObj.parse ~ InnerObj.parse *) // this is what creates the list of tuples

标签: scala anorm
1条回答
倾城 Initia
2楼-- · 2019-08-08 21:49
tuples                            // List[(A, B)]
    .groupBy(_._1)                // Map[A , List[(A, B)]
    .mapValues(_.map(_._2))       // Map[A, List[B]]
    .toList                       // List[(A, List[B])]
    .map{ case (parent, children) =>
        parent.copy(
            innerList = children
        )
    }                             // List[A]

Using an outer join you really ought to parse the inner objects optionally, otherwise you'll lose rows where there are no inner objects (unless that is the desired effect). In which case, you'd do:

SQL(...).as(OuterObj.parse ~ (InnerObj.parse ?) *) // List[(A, Option[B])]                    
    .groupBy(_._1)                // Map[A , List[(A, Option[B])]
    .mapValues(_.map(_._2))       // Map[A, List[Option[B]]]
    .toList                       // List[(A, List[Option[B]])]
    .map{ case (parent, children) =>
        parent.copy(
            innerList = children.flatten
        )
    }                             // List[A]
查看更多
登录 后发表回答