简体   繁体   English

如何在Scala中将Seq [Object]转换为Map [User,Set [String]

[英]How to convert Seq[Object] to Map[User, Set[String] in Scala

It's really hard to explain in the title but here's what I want to do. 标题中确实很难解释,但这是我想要做的。

I'm pretty new to Scala. 我是Scala的新手。 I have an object User which is just a user that two users can be equal given the same user id 我有一个对象User ,它只是一个用户,给定相同的用户ID,两个用户可以相等

case class UserCustomFeature(
  hobby: String,
  users: Set[User]
) {}

My input is Seq[UserCustomFeature] So basically a list of objects of a hobby -> users. 我的输入是Seq[UserCustomFeature]因此基本上是一个爱好的对象列表->用户。 For example, 例如,

[('tv' -> Set('user1', 'user2')),
('swimming' -> Set('user2', 'user3'))]

And I want the result to be 我希望结果是

('user1' -> Set('tv')),
('user2' -> Set('tv', 'swimming')),
('user3' -> Set('swimming'))

I have something like this so far but I'm not sure how to group them later 到目前为止,我有类似的内容,但是我不确定以后如何将它们分组

userHobbyMap
      .map({
        case (hobby, users) => {
          users.map(user => {
            (user, hobby)
          })
        }
      })
case class User(id: String)
case class UserCustomFeature(
  hobby: String,
  users: Set[User]
) {}

val input = Seq(
  UserCustomFeature("tv", Set(User("1"), User("2"))),
  UserCustomFeature("swimming", Set(User("2"), User("3")))
)

val output = (for (UserCustomFeature(h, us) <- input; u <- us) yield (u, h))
  .groupBy(_._1)
  .mapValues(_.map(_._2).toSet)

output foreach println

Generates output: 产生输出:

(User(1),Set(tv))
(User(3),Set(swimming))
(User(2),Set(tv, swimming))

Brief explanation: 简要说明:

  • for -comprehension transposes the sequence of UserCustomFeature s into a list of (user, hobby) pairs. for -comprehension调换的序列UserCustomFeature s转换的列表(user, hobby)对。
  • groupBy groups hobbies by user (first component) groupBy按用户分组兴趣(第一个组件)
  • The map(_._2) drops the redundant user id from grouped pairs map(_._2)从分组对中删除冗余用户ID
  • toSet converts the resulting list of hobbies to a set of hobbies toSet将所产生的兴趣列表转换为一组兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM