Scala案例对象序列的组concat

时间:2019-03-09 13:21:31

标签: scala functional-programming

我想知道是否有一种优雅的方法可以通过纯scala为scala case对象的seq进行分组连接。这是我的方法。

case class UserToAccounts
(
  id: Int,
  email: String,
  firstName: String,
  lastName: String,
  accountId: Seq[Int]
)

case class User
(
  id: Int,
  email: String,
  firstName: String,
  lastName: String,
  accountId: Int
)

val users = Seq(
  User(1, "foo@test.com", "test", "foo", 1),
  User(1, "foo@test.com", "test", "foo", 2),
  User(2, "bar@test.com", "test", "bar", 1)
)

val groupedUsers = users
      .groupBy(u => (u.id, u.email, u.firstName, u.lastName))
      .mapValues( x => x.map( y => y.accountId))
      .map(z => UserToAccounts(
      id = z._1._1,
      email = z._1._2,
      firstName = z._1._3,
      lastName = z._1._4,
      accountIds = z._2
    ))

println(groupedUsers)

List(UserToAccounts(2,bar@test.com,test,bar,List(1)), UserToAccounts(1,foo@test.com,test,foo,List(1, 2)))

预先感谢您的好建议。

1 个答案:

答案 0 :(得分:1)

您应该只能够按id类的User进行分组,这将为您提供从User.idList[User]的地图。然后,您可以在其上进行映射并使用它直接创建您的UserToAccounts对象。您将需要map上的userList来提取该用户的所有帐户ID:

users.groupBy(_.id).map {
  case (userId, userList) =>
    val user = userList.head
    UserToAccounts(userId,
                   user.email,
                   user.firstName,
                   user.lastName,
                   userList.map(_.accountId))
}