[英]Refactoring java style to more functional scala style
我想將用戶的地圖轉換為朋友的地圖。 類型Username:字符串因此,通過將每個List [User]放入鍵,將Map [Username,List [User]]映射到Map [Username,List [Username]]。
我下面的代碼非常像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
}
我開始嘗試:
users.map( user =>
user.friends.flatMap(friend =>
)
附帶說明一下,由於某種原因,我該如何附加到ListBuffer上:
m.get(friend.username) += user
並新建一個列表緩沖區並追加將如何完成?
也許你想要
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
}
第二個問題:方法m.get(friend.username)返回Option [ListBuffer [User]]。 選項不包含+ =。
一線解決方案
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.