假设我有List[Map[String, String]]
表示数据库中的表,而List[String]
表示列名列表。我想在group by
查询中实现等效的SQL
子句:
def fun(table:List[Map[String, String]], keys:List[String]): List[List[Map[String, String]]
例如:
val table = List(
Map("name"->"jade", "job"->"driver", "sex"->"male"),
Map("name"->"mike", "job"->"police", "sex"->"female"),
Map("name"->"jane", "job"->"clerk", "sex"->"female"),
Map("name"->"smith", "job"->"driver", "sex"->"male")
)
val keys = List("job", "sex")
然后fun(table,keys)
应该是:
List(
List(
Map("name"->"jade", "job"->"driver", "sex"->"male"),
Map("name"->"smith", "job"->"driver", "sex"->"male")
),
List(Map("name"->"mike", "job"->"police", "sex"->"female")),
List(Map("name"->"jane", "job"->"clerk", "sex"->"female"))
)
答案 0 :(得分:1)
您正在寻找groupBy
:
table.groupBy(row => keys.map(key => row(key))) map {
case (group, values) => values
}
或者更简洁:
table.groupBy(keys.map(_)).map(_._2)