Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一堂课叫 Group
class Group(id: Int, name: String, category: String) { }
我正在尝试转换Array[Group]为Map[String, Seq[Group]]withcategory: String作为键。Seq[Group]如果密钥不存在,我想创建一个空并添加组,否则更新Seq[Group]. 如果密钥已经存在,我不确定如何更新 Seq。
Array[Group]
Map[String, Seq[Group]]
category: String
Seq[Group]
groupBy会做这一切。
arrayOfGroups.groupBy(_.category)
只是结果将是一个Map[String, Array[Group]](因为原始容器是一个数组)。数组不完全是 Seq,所以如果你想要一个,你可以这样做
Map[String, Array[Group]]
arraysOfGroup.groupBy(_.category).mapValues(_.toSeq)
您可以用toSeq任何更精确的转换替换 。也可以这样做arrayOfGroup.toSeq.groupBy(_.category)
toSeq
arrayOfGroup.toSeq.groupBy(_.category)