我有一个List [User],我想创建一个地图,我可以在其中查找locationId并获取与该locationId相关联的所有用户的列表。
case class User(id: Int, locationId: Int, ....)
我现在的代码非常像java,希望有人可以帮助将其转换为更惯用的scala。我正在使用可变列表,但在这种情况下他们可能必须在这里。
lazy val usersMap: Map[Int, mutable.ListBuffer[User]] = {
val map = new mutable.HashMap[Int, mutable.ListBuffer[User]]
for(user <- users) {
if(map.contains(user.locationId)) {
map(user.locationId) += user
} else {
val lb = mutable.ListBuffer.empty[User]
lb += user
map.put(user.locationId, lb)
}
}
map.toMap
}
我的另一个要求是通过user.Id对List [User]进行排序。所以当我做map(3)时,我得到一个已经按user.id
排序的用户列表答案 0 :(得分:4)
假设您从一些List[User]
开始,您可以使用groupBy
创建Map[Int, List[User]]
,其中每个密钥都是唯一的locationId
,每个List[User]
地图内的locationId
作为其关键字。然后,为了对每个用户列表进行排序,您可以对结果mapValues
使用Map
。
val users = List(User(1, 1), User(2, 1), User(3, 4), User(4, 5), User(7, 4), User(8, 5))
lazy val usersMap: Map[Int, List[User]] =
users.groupBy(_.locationId).mapValues(_.sortBy(_.id))
usersMap: scala.collection.immutable.Map[Int,List[User]] = Map(
5 -> List(User(4,5), User(8,5)),
4 -> List(User(3,4), User(7,4)),
1 -> List(User(1,1), User(2,1))
)