如何在scala中实现动态组?

时间:2015-03-26 16:36:11

标签: scala

假设我有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"))
)

1 个答案:

答案 0 :(得分:1)

您正在寻找groupBy

table.groupBy(row => keys.map(key => row(key))) map { 
    case (group, values) => values 
}

或者更简洁:

table.groupBy(keys.map(_)).map(_._2)