简体   繁体   English

将Java样式重构为功能更强大的Scala样式

[英]Refactoring java style to more functional scala style

I want to transform a map of users to their friends to a map of friends to their friends. 我想将用户的地图转换为朋友的地图。 type Username: String So Map[Username, List[User]] to Map[Username, List[Username]] by making each List[User] into the key. 类型Username:字符串因此,通过将每个List [User]放入键,将Map [Username,List [User]]映射到Map [Username,List [Username]]。

I have the following code below that is very java like that I want to refactor to make it more idomatic scala code. 我下面的代码非常像Java,我想对其进行重构以使其更加像idomatic scala代码。

val map: Map[String, List[User]] = {
  var m  = collection.mutable.Map[String, collection.mutable.ListBuffer[User]]()
  for(user <- users) {
    for(friend <- user.Friends) {
      if (m.contains(friend)) {
        //m.get(friend.username) += user
      } else {
        m += (friend -> collection.mutable.ListBuffer[User]())
        //m.get(friend.username) += user
      }
    }
  }
  m.map{e =>
    (e._1 -> e._2.toList)}.toMap
}

I started off trying this: 我开始尝试:

users.map( user =>
  user.friends.flatMap(friend =>

)

As a side note, how do I append to a ListBuffer, for some reason this was not working for me: 附带说明一下,由于某种原因,我该如何附加到ListBuffer上:

m.get(friend.username) += user

And to new-up a listbuffer and append would be done how? 并新建一个列表缓冲区并追加将如何完成?

Maybe you would like 也许你想要

    val map: Map[String, List[User]] = {
        val m = new collection.mutable.HashMap[String, collection.mutable.Set[User]]() with scala.collection.mutable.MultiMap[String, User]
        for {
            user <- users
            friend <- user.Friends
        }   m.addBinding(friend.username,user)

        m.mapValues(x ⇒ x.toList).toMap
    }

And second question: method m.get(friend.username) returns Option[ListBuffer[User]]. 第二个问题:方法m.get(friend.username)返回Option [ListBuffer [User]]。 Option not contains +=. 选项不包含+ =。

Update 更新资料

One line solution 一线解决方案

    val map: Map[String, Seq[User]] = {
        users.flatMap(user ⇒ user.Friends.map(_ → user)).groupBy(_._1.username).mapValues(_.map(_._2))
    }

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

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